Python 3D Academyবাংলা

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:

  1. await asyncio.wait_for(job(), 2) gives job() at most 2 seconds; if it isn't done by then, it's cancelled and TimeoutError is raised, which you can catch
  2. async with asyncio.timeout(2): puts the same limit around a whole block of awaits
  3. async with asyncio.TaskGroup() as tg: with tg.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 an ExceptionGroup. 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 one
  • asyncio.TaskGroup: tasks made with tg.create_task belong 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())
Slow Kitchen would take 1 second, but wait_for gives up after 0.2 and cancels it.

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())
When the toast fails, the group cancels the dal (still cooking) and raises the error. except* catches the ValueError out of the group.

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, not ValueError.
  • 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 the async with block has finished.
  • One failure in a group. It cancels the others, and you get the error (inside an ExceptionGroup) when the block ends.

Quiz

  1. 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())
  2. 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())
  3. 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())
  4. 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
  5. Which error does asyncio.wait_for raise when the time runs out?

    • TimeoutError
    • ValueError
    • StopIteration
  6. 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

  1. Write async def with_limit(job, secs): await the coroutine job with asyncio.wait_for, giving it at most secs seconds, and give back its result, or the text "too slow" if it runs out of time. (dish is a slow job written for you.)

  2. Write async def cook_all(orders) with an asyncio.TaskGroup: orders is a dict of dish to seconds. Cook every dish at the same time with cook (written for you) and give back the results in a list, in the order of orders.