The cancel function allows us to request the cancellation of futures or coroutines:
import asyncio
async def myCoroutine():
print("My Coroutine")
async def main():
current = asyncio.Task.current_task()
print(current)
loop = asyncio.get_event_loop()
try:
task1 = loop.create_task(myCoroutine())
task2 = loop.create_task(myCoroutine())
task3 = loop.create_task(myCoroutine())
task3.cancel()
loop.run_until_complete(main())
finally:
loop.close()
Upon execution of the preceding program, you should see that both task1 and task2 are successfully executed. The third task that we scheduled, due to the cancel call we made, is never actually executed.
Now, this is just a simple example of how we can cancel a task, and we did it in such a way that we pretty much guarantee our third task is cancelled. However, out in the wild, there is no guarantee that the cancel function will definitely cancel your pending task:
$ python3.6 16_asyncioTasks.py
My Coroutine
My Coroutine
<Task pending coro=<main() running at 16_asyncioTasks.py:8> cb=[_run_until_complete_cb() at /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py:176]>