Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to wait in Python

Introduction

As you start learning programming, you will come across scenarios where you need to wait for certain events or delay the execution of your code. In Python, there are several ways to achieve this, and this blog post will guide you through the different techniques, how they work, and when to use them.

We will be covering the following topics:

  1. time.sleep()
  2. threading.Timer()
  3. asyncio.sleep()
  4. schedule library

Why do we need to wait in Python?

Before we dive into the methods, let's understand why we might need to wait in our Python programs. Here are a few reasons:

  1. Rate limiting: If you're working with an external API or a shared resource, you may need to limit the number of requests you make per second to avoid overwhelming the server or getting blocked.
  2. Synchronization: In multi-threaded or multi-process applications, you may need to wait for other tasks to complete before proceeding.
  3. User experience: In some cases, you may want to add a delay to make your program more user-friendly. For example, you can display a loading message before rendering the results of a complex calculation.

Now that we know why waiting is important, let's explore the different techniques to achieve it in Python.

1. time.sleep()

The simplest way to add a delay to your Python program is by using the time.sleep() function. This function is part of the built-in time module and takes a single argument: the number of seconds to sleep.

How does it work?

The time.sleep() function blocks the execution of the current thread for the specified number of seconds. This means that the program will pause, and nothing else will happen until the sleep is over.

Example

Here's a simple example that demonstrates how to use time.sleep():

import time

print("Start")
time.sleep(2)  # Sleep for 2 seconds
print("End")

When you run this code, you'll see the "Start" message, then there will be a delay of 2 seconds, and finally, the "End" message will be printed.

When to use time.sleep()

time.sleep() is suitable for simple scripts and single-threaded applications where you need to add a basic delay. However, it is not recommended for more complex programs that require concurrency, as it blocks the execution of the entire thread.

2. threading.Timer()

If you need more control over when your code should resume execution, you can use the threading.Timer() class from the threading module. This class allows you to run a function after a specified delay without blocking the main thread.

How does it work?

threading.Timer() creates a new thread that will execute the specified function after the given delay. This means that your main thread can continue running while the timer is active.

Example

Here's an example that demonstrates how to use threading.Timer():

import threading

def delayed_function():
    print("Hello, world!")

print("Start")
timer = threading.Timer(2, delayed_function)  # Set a timer to run the function after 2 seconds
timer.start()
print("End")

When you run this code, you'll see the "Start" message, followed immediately by the "End" message. After a 2-second delay, the "Hello, world!" message will be printed.

When to use threading.Timer()

threading.Timer() is suitable for situations where you need to execute a function after a delay without blocking the main thread. However, it is not suitable for tasks that require precise timing or for applications that use multiple threads and need to coordinate their activities.

3. asyncio.sleep()

If you are working with asynchronous code, you can use the asyncio.sleep() function to pause the execution of a coroutine without blocking the event loop.

How does it work?

asyncio.sleep() is a coroutine that yields control back to the event loop, allowing other tasks to run while waiting for the specified delay to elapse. This means that your program can continue processing other tasks without blocking.

Example

Here's an example that demonstrates how to use asyncio.sleep():

import asyncio

async def delayed_function():
    print("Start")
    await asyncio.sleep(2)  # Sleep for 2 seconds without blocking
    print("End")

async def main():
    await delayed_function()

asyncio.run(main())

When you run this code, you'll see the "Start" message, then there will be a delay of 2 seconds, and finally, the "End" message will be printed.

When to use asyncio.sleep()

asyncio.sleep() is suitable for asynchronous applications that need to add a delay while allowing other tasks to continue running. It is not recommended for synchronous or multi-threaded applications, as it requires an event loop to function correctly.

4. Schedule library

If you need to run a function at specific intervals or at certain times, you can use the schedule library. This library provides a simple and human-readable syntax to schedule tasks in Python.

How does it work?

schedule allows you to define jobs that run at specific intervals or times. The library uses a simple loop to check if any jobs are due to run and executes them accordingly.

Example

Here's an example that demonstrates how to use the schedule library:

import schedule
import time

def job():
    print("Hello, world!")

schedule.every(5).seconds.do(job)  # Schedule the job to run every 5 seconds

while True:
    schedule.run_pending()  # Check for and run any pending jobs
    time.sleep(1)  # Sleep for 1 second to avoid excessive CPU usage

When you run this code, the "Hello, world!" message will be printed every 5 seconds.

When to use the schedule library

The schedule library is suitable for applications where you need to run tasks at specific intervals or times. It is not recommended for applications that require precise timing or complex scheduling, as it relies on a simple loop to check for pending jobs.

Conclusion

In this blog post, we've explored four different ways to wait in Python:

  1. time.sleep() for simple delays in single-threaded applications
  2. threading.Timer() for running a function after a delay without blocking the main thread
  3. asyncio.sleep() for adding delays in asynchronous applications without blocking the event loop
  4. The schedule library for scheduling tasks to run at specific intervals or times

Now you should have a better understanding of when to use each method, and you can choose the most suitable one for your Python projects. Happy coding!