await asyncio.sleep
- Python course
- Advanced
- Lesson 28/83
- 5 min
Learn waiting with await asyncio.sleep.
await asyncio.sleep
asyncio.sleep is the async counterpart of time.sleep. It waits a given duration without blocking the event loop; other coroutines can run in the meantime.
async def task():
print("start")
await asyncio.sleep(0)
print("end")Here await asyncio.sleep(0) yields control to the event loop so other coroutines can run. The control point applies even with zero seconds.
time.sleep instead freezes the whole program; that's why it is not used in async code.
Waiting and control points
When a coroutine reaches an await point, it yields control to the event loop. The loop moves to another pending coroutine. This is the basis of the concurrent appearance.
Wait times are in seconds; they can be fractional. await asyncio.sleep(0.5) waits half a second. Even with zero, control is yielded.
This model gives high concurrency even under the GIL: while waiting on I/O, other work happens.
Practice Write task with await asyncio.sleep
Start with import asyncio. The function async def task() first prints print("start"), then await asyncio.sleep(0), finally print("end") and return "ok". Add print(asyncio.run(task())).
Starter code
# import the asyncio module
# declare a coroutine named task; print start, wait zero seconds, print end, return ok
# print the result of task via asyncio.runSample solution
import asyncio
async def task():
print("start")
await asyncio.sleep(0)
print("end")
return "ok"
print(asyncio.run(task()))Expected output
start end ok
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is time.sleep not used in async code?
- Because it is slower
- Because it raises errors
- Because it blocks the event loop Correct answer
- Because it only works on Windows
Explanation: time.sleep freezes the whole program; other coroutines cannot run.
2 asyncio.sleep call
import asyncio
async def task():
await ____(0)
import asyncio
async def task():
await asyncio.sleep(0)
Explanation: asyncio.sleep(0) yields control to the event loop.
3 Match the sleep concepts
| Term | Meaning |
|---|---|
asyncio.sleep |
Non-blocking wait |
time.sleep |
Blocks |
await asyncio.sleep(0) |
Control point |
await asyncio.sleep(0.5) |
Half a second |