Overview:
-
A Task is created and scheduled for its execution through the asyncio.create_task() function.
-
Once scheduled, a Task can be requested for cancellation through task.cancel() method.
-
If successful, a CancelledError is thrown into the coroutine corresponding to the Task.
Example:
# Example Python program that makes a cancellation # Define a coroutine
# Make a cancellation request # Wait for the cancellation of t1 to be complete # Create a new event loop and set to asyncio # Run the coroutine containing tasks
|
Output:
Task entered:2022-05-06 12:05:12.124871 Beep...1 Beep...2 Beep...3 Beep...4 Beep...5 Stopping the alarm Alarm stopped Task cancelled:2022-05-06 12:05:17.130425 Hello world |