liveBook · Manning

Task cancellation

As explained in Python Concurrency with asyncio

Task cancellation is the cooperative termination of an asynchronous task by requesting that it stop at a cancellation point.

Task cancellation cooperatively stops an asynchronous task by requesting termination. Calling a task’s cancel method does not interrupt ordinary Python code immediately; cancellation is delivered as CancelledError at an await point. section 2.4.1

Use cancellation to keep asynchronous applications responsive and prevent work from running indefinitely.

  • Cancel a task directly when an elapsed-time check, user action, or application condition says it should stop. section 2.4 section 2.4.1
  • Await the canceled task and handle CancelledError so cancellation produces an intentional result rather than an unhandled failure. section 2.4.1
  • Prefer asyncio.wait_for for a timeout that automatically cancels work, then catch TimeoutError and inspect whether the task was canceled. section 2.4.2
  • Wrap a task with asyncio.shield when a timeout should notify the caller without canceling the underlying work. section 2.4.2
  • Cancel pending tasks after asyncio.wait returns on FIRST_EXCEPTION when one failed request makes remaining work unnecessary. section 4.6.2

Stopping a long-running task

Create a ten-second delay, check it once per second, and call cancel after five seconds. Awaiting the task then raises CancelledError, allowing the program to report that the operation was stopped. section 2.4.1

Listing 2.11 Canceling a task
import asyncio
from asyncio import CancelledError
from util import delay
 
 
async def main():
    long_task = asyncio.create_task(delay(10))
 
    seconds_elapsed = 0
 
    while not long_task.done():
        print('Task not finished, checking again in a second.')
        await asyncio.sleep(1)
        seconds_elapsed = seconds_elapsed + 1
        if seconds_elapsed == 5:
            long_task.cancel()
 
    try:
        await long_task
    except CancelledError:
        print('Our task was cancelled')
 
asyncio.run(main())

Runnable example showing task creation, periodic progress updates, cancellation after five seconds, and CancelledError handling. section 2.4.1

How Python Concurrency with asyncio covers it

How deep it goes
Explains direct cancellation, await-point delivery, exception handling, timeouts, shielding, and pending-task cleanup without descending into runtime internals.
Examples
Demonstrates a timed delay, periodic status checks, wait_for timeout handling, shielded completion, and canceled aiohttp requests.
What it assumes
Assumes familiarity with asyncio tasks, coroutines, await, and concurrent execution while establishing cancellation behavior through runnable delays.
What you can do after
Apply it via asyncio task APIs to stop work, enforce time limits, preserve selected tasks, and clean up requests after failures.
How it connects
Connects tasks with await statements, CancelledError, timeouts, asyncio.wait_for, asyncio.shield, asyncio.wait, and graceful shutdown.

Also explained in

Compare how 5 books explain task cancellation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.