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




