Back
+15 XP
Concept

Async Timeouts with asyncio.wait_for

Unresponsive network endpoints can stall your event loop forever. `asyncio.wait_for(coro, timeout)` cancels the task and raises `TimeoutError` if it takes too long ⏱️.

python
import asyncio

async def slow_query():
    await asyncio.sleep(5.0)
    return "Data"

async def main():
    try:
        await asyncio.wait_for(slow_query(), timeout=0.05)
    except TimeoutError:
        return "Query timed out! ⏱️"

print(asyncio.run(main()))  # 'Query timed out! ⏱️'

# 47. Async Timeouts with asyncio.wait_for Unresponsive network endpoints can stall your event loop forever. `asyncio.wait_for(coro, timeout)` cancels the task and raises `TimeoutError` if it takes too long ⏱️. ```python import asyncio async def slow_query(): await asyncio.sleep(5.0) return "Data" async def main(): try: await asyncio.wait_for(slow_query(), timeout=0.05) except TimeoutError: return "Query timed out! ⏱️" print(asyncio.run(main())) # 'Query timed out! ⏱️' ``` When a timeout fires, `asyncio.wait_for` automatically cancels the underlying coroutine, saving system resources and preventing ghost background tasks! ⏱️ --- ### Question What exception is raised when a task exceeds the deadline in `asyncio.wait_for()`? 🧠 - [ ] a. `TimeoutError` ⏱️ - [ ] b. `DeadlockError` - [ ] c. `BrokenPipeError` - [ ] d. `InterruptedError` --- ### Challenge Write an async function `hang_forever()` that does `await asyncio.sleep(10)`. In `test()`, wrap it in `try / except TimeoutError` with `asyncio.wait_for(hang_forever(), timeout=0.01)` and return `'Handled'`. Run with `asyncio.run()` and print result. 🎯 <details> <summary>Solution</summary> ```python import asyncio async def hang_forever(): await asyncio.sleep(10) async def test(): try: await asyncio.wait_for(hang_forever(), timeout=0.01) except TimeoutError: return "Handled" print(asyncio.run(test())) ``` </details>

Checkpoint

What exception is raised when a task exceeds the deadline in `asyncio.wait_for()`? 🧠

Practice

Write an async function `hang_forever()` that does `await asyncio.sleep(10)`. In `test()`, wrap it in `try / except TimeoutError` with `asyncio.wait_for(hang_forever(), timeout=0.01)` and return `'Handled'`. Run with `asyncio.run()` and print result. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks