How to set a timeout with asyncio.wait_for in Python
Use asyncio.wait_for to bound an async function with a timeout, catching TimeoutError when it exceeds the limit.
Python code
15 linesimport asyncio
async def slow_task():
await asyncio.sleep(3)
return "finished"
async def main():
try:
result = await asyncio.wait_for(slow_task(), timeout=1)
print(result)
except asyncio.TimeoutError:
print("Task timed out")
if __name__ == "__main__":
asyncio.run(main())
Output
Task timed out
How it works
asyncio.wait_for runs the coroutine slow_task() with a maximum duration. If the task doesn't finish within timeout, it cancels the task and raises asyncio.TimeoutError. The try/except block catches that error, allowing graceful handling. Since slow_task() sleeps 3 seconds but timeout is 1, it always times out. asyncio.run sets up and tears down the event loop automatically.
Common mistakes
- Importing TimeoutError from builtins instead of asyncio.TimeoutError
- Passing a coroutine object instead of awaiting it directly with wait_for
- Forgot to handle cancellation side effects in the task
Variations
- Use `asyncio.timeout(1)` (Python 3.11+) as a context manager for cleaner syntax
- Wrap multiple coroutines with `asyncio.gather` and set an overall timeout
Real-world use cases
- Enforcing API call limits to avoid hanging upstream HTTP requests in a web service.
- Bounding database queries or slow I/O operations so a job doesn't block forever.
- Adding a watchdog to a long-running background task that must fail fast on hung dependencies.
Sponsored
More from Concurrency & performance
- Benchmark list.append vs deque.append in Python medium
- Build a Python Performance Profiler That Generates Readable Reports medium
- Graceful Shutdown Executor Context Manager in Python medium
- How to Build a Producer-Consumer Pattern with asyncio.Queue in Python medium
- How to Cancel an asyncio Task with Graceful Cleanup in Python medium
- How to Convert Data in Parallel with ThreadPoolExecutor in Python easy
Keep learning
Related tutorials and quizzes for this topic.