Time limits and task groups
🌍 In real life. A food delivery app sends your order to a restaurant. If the restaurant hasn't confirmed within a time limit, the app stops waiting and tries another one. Waiting for ever isn't an option.
asyncio has tools for both halves of that, step by step:
await asyncio.wait_for(job(), 2)givesjob()at most 2 seconds; if it isn't done by then, it's cancelled andTimeoutErroris raised, which you can catchasync with asyncio.timeout(2):puts the same limit around a whole block of awaitsasync with asyncio.TaskGroup() as tg:withtg.create_task(...)inside starts several tasks and waits for all of them at the end of the block. If one raises an error, the group cancels the others and raises the errors together as anExceptionGroup. That's safer than leaving the others running
The idea in one sentence: asyncio.wait_for(coro, seconds) gives up with a TimeoutError if a coroutine takes too long, and a TaskGroup runs several tasks that all finish (or all get cancelled) together.
Its words:
- timeout: a time limit after which you stop waiting
asyncio.wait_for(coro, 0.5)/async with asyncio.timeout(0.5):two ways to set oneasyncio.TaskGroup: tasks made withtg.create_taskbelong to the group- cancel: stop a task at its next
await
import asyncio
async def restaurant(name, secs):
await asyncio.sleep(secs)
return name + " confirmed"
async def order(name, secs):
try:
return await asyncio.wait_for(restaurant(name, secs), 0.2)
except TimeoutError:
return name + " too slow, trying another"
async def main():
print(await order("Spice Hub", 0.1))
print(await order("Slow Kitchen", 1))
asyncio.run(main())A group that finishes together. A TaskGroup is gather with a safety net. Every task made with tg.create_task belongs to the group, and the async with block doesn't end until all of them have. Each task's result is task.result() once the block is done.
import asyncio
async def cook(dish, secs):
await asyncio.sleep(secs)
if dish == "burnt toast":
raise ValueError("the toast caught fire")
return dish
async def main():
async with asyncio.TaskGroup() as tg:
rice = tg.create_task(cook("rice", 0.2))
egg = tg.create_task(cook("egg", 0.1))
print(rice.result(), egg.result())
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(cook("dal", 0.3))
tg.create_task(cook("burnt toast", 0.1))
except* ValueError as group:
print("kitchen problem:", group.exceptions[0])
asyncio.run(main())Why time limits and groups? A program that waits for ever on one slow server is as stuck as one that crashed. A timeout turns "maybe never" into a clear error you can handle. A TaskGroup makes sure no task is left running on its own: if one fails, the others are cancelled, and the error reaches you.
Mistakes and edge cases.
- Catching the wrong error. A timeout raises
TimeoutError; catch that, notValueError. - Expecting the slow task to keep going. After a timeout, the coroutine is cancelled at its next
await. - Reading results inside the block.
task.result()is ready only after theasync withblock has finished. - One failure in a group. It cancels the others, and you get the error (inside an ExceptionGroup) when the block ends.
Quiz
What does this print?
import asyncio async def slow(): await asyncio.sleep(1) return "late" async def main(): try: print(await asyncio.wait_for(slow(), 0.1)) except TimeoutError: print("gave up") asyncio.run(main())What does this print?
import asyncio async def quick(): await asyncio.sleep(0.05) return "on time" async def main(): print(await asyncio.wait_for(quick(), 1)) asyncio.run(main())What does this print?
import asyncio async def square(n): await asyncio.sleep(0.01 * n) return n * n async def main(): async with asyncio.TaskGroup() as tg: a = tg.create_task(square(3)) b = tg.create_task(square(2)) print(a.result() + b.result()) asyncio.run(main())In a TaskGroup, one task raises an error. What happens to the others?
- The group cancels them, then raises the error
- They keep running in the background
- Python restarts the failed task
Which error does
asyncio.wait_forraise when the time runs out?- TimeoutError
- ValueError
- StopIteration
The order takes too long, but the program crashes instead of printing too slow. Which line catches the wrong error?
import asyncio async def confirm(): await asyncio.sleep(1) async def main(): try: await asyncio.wait_for(confirm(), 0.1) except ValueError: print("too slow") asyncio.run(main())
Coding tasks
Write
async def with_limit(job, secs): await the coroutinejobwithasyncio.wait_for, giving it at mostsecsseconds, and give back its result, or the text"too slow"if it runs out of time. (dishis a slow job written for you.)Write
async def cook_all(orders)with anasyncio.TaskGroup:ordersis a dict of dish to seconds. Cook every dish at the same time withcook(written for you) and give back the results in a list, in the order oforders.