Apply a deadline with an async context manager.
Section: Cancellation and Timeouts
Use `asyncio.timeout()`
python
python
import asyncio
async def main():
try:
async with asyncio.timeout(0.2):
await asyncio.sleep(1)
except TimeoutError:
print("timed out")
asyncio.run(main())Explanation
Modern timeout pattern for scoped async operations.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Cancellation and Timeouts
Shield a task from outer cancellation
Prevent cancellation from immediately propagating to a task.
Add a timeout to queue operations
Wrap queue operations with `wait_for()`.
Run an async entrypoint
Execute a top-level coroutine and manage the event loop automatically.