Request cancellation and await the task to observe it.

Section: Cancellation and Timeouts

Cancel a task

python
python
import asyncio

async def worker():
    try:
        await asyncio.sleep(10)
    except asyncio.CancelledError:
        print("clean up before exit")
        raise

async def main():
    task = asyncio.create_task(worker())
    await asyncio.sleep(0.1)
    task.cancel()
    try:
        await task
    except asyncio.CancelledError:
        print("task cancelled")

asyncio.run(main())
Explanation

Cancellation is cooperative. Handle `CancelledError` for cleanup, then re-raise.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Cancellation and Timeouts
Use `asyncio.wait_for()`
Wrap an awaitable with a timeout.
OpenIn sheetpythonsame section
Use `asyncio.timeout()`
Apply a deadline with an async context manager.
OpenIn sheetpythonsame section
Shield a task from outer cancellation
Prevent cancellation from immediately propagating to a task.
OpenIn sheetpythonsame section
Create a background task
Schedule a coroutine to run concurrently.
OpenIn sheetpython1 tag match
Run an async entrypoint
Execute a top-level coroutine and manage the event loop automatically.
Use an asyncio.Queue
Exchange work between producers and consumers.