Timeouts and Cancellation
Why timeouts matter
Network calls can stall.
Always use timeouts to avoid:
- stuck tasks
- resource leaks
asyncio.wait_for
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())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())Cancelling a task
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())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())Best practices
- Consider timeouts for all external calls.
- Always handle cancellation cleanly.
๐งช Try It Yourself
Exercise 1 โ asyncio.wait_for Timeout
Exercise 2 โ Cancel a Task
Exercise 3 โ Check Cancellation
If this helped you, consider buying me a coffee โ
Buy me a coffeeWas this page helpful?
Let us know how we did
