Книга: Learning Concurrency in Python
Назад: The all_tasks(loop=None) method
Дальше: The cancel() function

The current_tasks() function

Gauging what current tasks are executing can be useful in a number of situations. If needed, you could effectively iterate through the list of current tasks executing on the event loop and attempt to cancel them if you wish.

In this example, we will schedule three distinct tasks using the create_task function and pass in our myCoroutine function as its input:

import asyncio
async def myCoroutine():
print("My Coroutine")

async def main():
current = asyncio.Task.current_task()
print(current)

loop = asyncio.get_event_loop()
try:
loop.create_task(myCoroutine())
loop.create_task(myCoroutine())
loop.create_task(myCoroutine())
loop.run_until_complete(main())
finally:
loop.close()

Upon execution, you should see that the coroutines are all successfully executed, and by the time our main coroutine is executed, the only coroutine pending is the one currently executing:

$ python3.6 16_asyncioTasks.py
My Coroutine
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]>
Назад: The all_tasks(loop=None) method
Дальше: The cancel() function