How to Sleep in Python (adding delays)
Python provides several sleep functions that allow us to add delays to our code. Let’s explore the
sched.scheduler.enter() functions to achieve this functionality.
import time print("Starting sleep for 5 seconds") time.sleep(5) print("Waking up after 5 seconds")
time.sleep() function is a fairly straightforward way to add delays to our Python code.
It takes in one argument, the number of seconds to sleep, which can be a decimal or integer value.
This function will block the execution of the program, meaning it will wait for the specified time before continuing.
InterruptedError exception will be raised if the sleep is interrupted by some signal.
import asyncio async def delay_print(delay, message): await asyncio.sleep(delay) print(message) async def main(): print("Starting sleep for 5 seconds") await delay_print(5, "Waking up after 5 seconds") asyncio.run(main())
asyncio.sleep() is similar to
time.sleep(), but it’s used in asynchronous programming.
This function also takes in a single argument representing the number of seconds to sleep.
time.sleep() is blocking,
asyncio.sleep() is non-blocking, meaning it will allow the rest of our program to continue while it waits for the specified time.
This function is best used for longer delays, especially in asynchronous programs where we might wait for a task to complete without blocking the event loop. It returns a coroutine, which can be awaited.
import sched, time s = sched.scheduler(time.time, time.sleep) def delay_print(sc, delay, message): print(message) s.enter(delay, 1, delay_print, (sc, delay, message)) print("Starting sleep for 5 seconds") s.enter(5, 1, delay_print, (s, 5, "Waking up after 5 seconds")) s.run()
sched.scheduler.enter() function is a slightly more complex but more powerful way to schedule events.
This one takes multiple arguments, including the time to enter the event, the priority, and the function to call when the event occurs.
sched.scheduler.enter() is also non-blocking and can be used to schedule events at specific times.