Pause execution in Python with sleep
Use time.sleep in synchronous code and asyncio.sleep in coroutines, with clear limits for timing accuracy, thread behavior, and recurring schedules.
Use time.sleep(seconds) to pause the calling thread. In an asyncio coroutine, use await asyncio.sleep(seconds) to suspend that task while allowing other tasks on the event loop to run.
Pause synchronous code
import time
print("Starting")
time.sleep(2)
print("Continuing")
The argument can be fractional: time.sleep(0.1) requests a tenth of a second. The sleeping thread cannot perform other work during that call, but other threads can continue to run.
Pause a coroutine
import asyncio
async def main():
print("Starting")
await asyncio.sleep(2)
print("Continuing")
asyncio.run(main())
Calling time.sleep() directly in the event-loop thread blocks that loop, delaying its other tasks. asyncio.sleep() provides cooperative suspension; it does not make unrelated blocking calls asynchronous.
Why a busy loop is usually the wrong choice
The following loop repeatedly checks the clock rather than sleeping:
import time
end = time.perf_counter() + 0.1
while time.perf_counter() < end:
pass
It can consume a CPU core while accomplishing no useful work. It also does not make Python a real-time scheduler or guarantee precise hardware timing. Use a sleep, event, or an appropriate scheduling facility for ordinary applications.
FAQ
How accurate is sleep? The requested delay is not an exact deadline. Scheduling and other activity can make the pause longer; an exception from a signal handler can interrupt the call. Do not promise a fixed millisecond error across operating systems and workloads.
Does one thread sleeping pause all threads? No, time.sleep() suspends the caller. If the caller is the event-loop thread, however, all tasks dependent on that loop must wait.
How do I run something every minute? A loop that performs work and then sleeps for 60 seconds has a period of work time plus 60 seconds. To reduce drift, calculate the next deadline with a monotonic clock and define what happens when work overruns it. For calendar schedules or persistent jobs, consider a scheduler such as APScheduler or system cron rather than an endless sleep loop.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan