How to sleep or delay n seconds in Python

Feb 19, 2024#python#async

In programming, sleeping or delaying execution refers to intentionally pausing the execution of a program for a specified period of time. This pause allows the program to wait before proceeding to the next instruction or task. Here are some common reasons:

  • Synchronize with external events or ensure that certain conditions are met.
  • Limit the rate of requests to avoid overwhelming the server.
  • Check periodically the condition without consuming excessive CPU resources.
  • Simulate a pause in a program, control the timing of certain actions.

The duration of sleep should be chosen carefully based on the specific use case. Too short a delay may cause unnecessary resource consumption, while too long a delay might make the program unresponsive.

In Python, there are several ways to introduce sleep or delay. The most common approach is using the time module’s sleep() function. For simple delays, using time.sleep() is usually sufficient.

Using time module

The time module provides various time-related functions. It includes functions for working with time, measuring time intervals, and introducing delays in the program. One of the commonly used functions in the time module for introducing delays is time.sleep().

import time

n = 5  # Replace with your desired number of seconds
time.sleep(n)

print("I woke up after", n, "seconds!")

Using asyncio module

The asyncio module provides a foundation for various Python asynchronous frameworks, including high-performance network servers, web servers, database connection libraries, and distributed task queues. It’s especially well-suited for IO-bound and high-level structured network code.

Using asyncio.sleep() to introduce a time delay is similar to time.sleep() but within an asynchronous context. Unlike time.sleep(), asyncio.sleep() doesn’t block the event loop, allowing other tasks to run concurrently.

import asyncio

async def my_async_function():
    print("Start")
    await asyncio.sleep(5)
    print("End")

Using threading module

The threading module provides tools for working with threads, which are lightweight sub-processes that allow your program to execute multiple tasks concurrently.

If you need subsecond precision, consider using the threading.Timer class. Import the threading module and create a timer object with the desired delay.

import threading

def print_message(message):
    print(message)

# Create a timer to print a message after 5 seconds
timer = threading.Timer(5, print_message, args=("Hello, world!",))
timer.start()