Skip to content

Timeouts and Cancellation

Network calls can stall.

Always use timeouts to avoid:

  • stuck tasks
  • resource leaks
wait_for.py
import asyncio
 
 
async def slow():
    await asyncio.sleep(5)
    return "ok"
 
 
async def main():
    try:
        result = await asyncio.wait_for(slow(), timeout=1)
        print(result)
    except asyncio.TimeoutError:
        print("timed out")
 
 
asyncio.run(main())
cancel_task.py
import asyncio
 
 
async def worker():
    try:
        while True:
            print("working")
            await asyncio.sleep(0.2)
    except asyncio.CancelledError:
        print("cancelled")
        raise
 
 
async def main():
    task = asyncio.create_task(worker())
    await asyncio.sleep(0.7)
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("task cancelled confirmed")
 
 
asyncio.run(main())
sketch A timeout only works if the code can be interrupted p5.js
Cancellation in asyncio is cooperative: the loop can only stop a task at an await. Three cases, all measured. A normal awaiting task under a 0.2 second timeout is cancelled on time. A task wrapped in shield survives the timeout and runs to completion even though the caller has already given up. And a blocking call with no await defeats the timeout entirely -- a 0.2 second limit around a blocking 0.8 second sleep returned after 0.80 seconds and raised nothing at all.
  • Consider timeouts for all external calls.
  • Always handle cancellation cleanly.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading