Python

asyncio.wait_for — Timeout Wrapper

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Cancel a coroutine if it takes longer than `timeout` seconds. Raises asyncio.TimeoutError when fired so the caller can fall back. Python 3.11+ has asyncio.timeout() as a context-manager alternative.
Python
Raw
import asyncio

async def slow_task():
    await asyncio.sleep(5)
    return "done"

async def main():
    try:
        result = await asyncio.wait_for(slow_task(), timeout=2.0)
        print(result)
    except asyncio.TimeoutError:
        print("Gave up after 2 seconds")

# Python 3.11+ alternative — context manager form, slightly more flexible:
async def main_modern():
    try:
        async with asyncio.timeout(2.0):
            await slow_task()
    except TimeoutError:
        print("Gave up after 2 seconds")

asyncio.run(main())
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.