Asyncio Cancel Propagation Graceful

Propagate cancellation through async tasks with cleanup for graceful shutdown.

PythonResilience

Code

snippet
import asyncio

async def worker(name, stop_event):
    try:
        while not stop_event.is_set():
            await asyncio.sleep(1)
            print(f'{name} working')
    except asyncio.CancelledError:
        print(f'{name} cleaning up')
        raise

async def main():
    stop = asyncio.Event()
    tasks = [asyncio.create_task(worker(f'w{i}', stop)) for i in range(3)]
    await asyncio.sleep(5)
    stop.set()
    for t in tasks:
        t.cancel()
    await asyncio.gather(*tasks, return_exceptions=True)