Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

How Python asyncio.sleep Works and When to Use It

Understand how Python asyncio.sleep yields control to the event loop, its cancellation behavior, and how it differs from time.sleep in async code.

~4 min readPython
#asyncio#concurrency#coroutines#event loop
Illustration of an asyncio event loop with a sleep timer yielding control to other tasks.

asyncio.sleep suspends the current task for a given number of seconds without blocking the event loop. When you await asyncio.sleep(delay), the current task yields control back to the event loop and other ready tasks can run. After the delay, the loop resumes the coroutine from the same await point. Use it in async code for delays, backoff, and cooperative yielding; use time.sleep in synchronous code or when blocking the whole thread is acceptable.

What asyncio.sleep Actually Does

asyncio.sleep suspends the current task for the requested number of seconds. The delay is not a hard deadline: if the event loop is busy with other callbacks or I/O, the task may resume later than requested. It guarantees only that the task will not resume before the delay elapses.

python
import asyncio async def main(): print("start") await asyncio.sleep(1) print("end") asyncio.run(main())

The await is essential. Calling asyncio.sleep(1) without await creates a coroutine object that is never awaited, so it does nothing and may produce a warning. Always use await when calling asyncio.sleep.

asyncio.sleep vs time.sleep

The most common mistake is using time.sleep inside an async function. time.sleep blocks the entire thread, preventing the event loop from running any other task. That defeats the purpose of concurrency and can cause serious performance problems in a server handling many connections.

Behaviorasyncio.sleeptime.sleep
Blocks the event loopNoYes
Requires awaitYesNo
CancellableYesNo
Used in async codeRecommendedAvoid
Used in sync codeNot applicableYes

In a synchronous script, time.sleep is appropriate. In an async function, use asyncio.sleep when you need a delay without blocking the loop.

Cancellation and Timeouts

One advantage of asyncio.sleep is that it participates in cancellation. When a task is cancelled, asyncio.CancelledError is raised at the current await point. This lets you perform cleanup or propagate the cancellation.

python
import asyncio async def worker(): try: await asyncio.sleep(10) except asyncio.CancelledError: print("worker cancelled") raise async def main(): task = asyncio.create_task(worker()) await asyncio.sleep(0.1) task.cancel() try: await task except asyncio.CancelledError: pass asyncio.run(main())

Because asyncio.sleep yields to the event loop, cancellation can be delivered while the task is sleeping. With time.sleep, cancellation cannot interrupt the blocking call, so the task would not stop until the sleep finishes.

In Python 3.11 and later, you can use asyncio.timeout to limit how long a coroutine is allowed to run:

python
import asyncio async def slow_operation(): await asyncio.sleep(5) return "done" async def main(): try: async with asyncio.timeout(1): result = await slow_operation() except TimeoutError: print("operation timed out") asyncio.run(main())

When the timeout expires, the task running the async with block is cancelled at its current await point, and the context manager raises TimeoutError.

Practical Patterns: Rate Limiting and Retries

asyncio.sleep is commonly used to implement rate limiting or backoff in async code. For example, a retry loop with exponential backoff:

python
import asyncio # fetch(url) is an async function that may raise ConnectionError async def fetch_with_retry(url, retries=3, base_delay=1): for attempt in range(retries): try: return await fetch(url) except ConnectionError: if attempt == retries - 1: raise delay = base_delay * (2 ** attempt) await asyncio.sleep(delay)

Because asyncio.sleep is non-blocking, other tasks continue to run during the backoff period. This matters in a server where you do not want to stall all requests while waiting to retry one.

Another pattern is throttling a loop that processes many items:

python
async def process_items(items): for item in items: await handle(item) # handle would be your async processing function await asyncio.sleep(0.05) # limit to 20 items per second

This keeps the loop from hammering a downstream service.

Performance and Event Loop Behavior

asyncio.sleep has a small overhead compared with time.sleep because it involves scheduling and resuming a coroutine. In most applications the overhead is negligible; the real benefit is that it does not block the event loop, allowing many concurrent tasks to share a single thread.

The event loop uses a monotonic clock to schedule wakeups. The delay is stored as a float, and the loop checks its timer queue on each iteration. For very short delays, asyncio.sleep still works, but the actual resolution depends on the operating system and the event loop's timer implementation.

One useful detail: asyncio.sleep(0) does not actually sleep. It yields to the event loop once, allowing other ready tasks to run, and resumes soon afterward. This is useful for cooperative multitasking when you want to give other tasks a chance without a real delay.

python
async def cooperative(): for i in range(10): print(i) await asyncio.sleep(0) # yield control

Common Mistakes and Edge Cases

A frequent mistake is using asyncio.sleep in a synchronous function. Because it is a coroutine, it must be awaited and requires a running event loop. If you need to sleep in a sync function, use time.sleep.

Another edge case is expecting precise timing. asyncio.sleep does not guarantee a hard real-time delay; if you need that, use a dedicated timer or a different scheduling mechanism. For most application-level delays, the soft guarantee is sufficient.

When cancelling a sleeping task, CancelledError is raised immediately at the await. If you have a finally block, it runs before the cancellation propagates. That can be useful for releasing resources, but avoid await asyncio.sleep(...) inside that finally block because it would delay cancellation handling.

Finally, since Python 3.11, asyncio.sleep accepts a result argument that is returned when the sleep completes:

python
value = await asyncio.sleep(1, result="ready") print(value) # prints "ready"

This is a minor convenience, but it can make code that needs to return a fixed value after a delay a little shorter.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.