Task manipulation with asyncio

The asyncio module provides the asyncio.Task() method to handle coroutines with tasks. The asyncio.Task class is a subclass of asyncio. Future and aims are used to manage coroutines. A task is responsible for the execution of a coroutine object in an event loop. When a coroutine is wrapped in a task, it connects the task to the event loop and then runs automatically when the loop is started, thus providing a mechanism to automatically drive the coroutine.

For more information on task manipulation with asyncio, check out the following documentation: https://docs.python.org/3.7/library/asyncio-task.html.

You can find the following code in the asyncio_task.py file:

#!/usr/bin/python3
import asyncio
import time

@asyncio.coroutine
def task_sleep(name, loop, seconds=1):
future = loop.run_in_executor(None, time.sleep, seconds)
print("[%s] coroutine will sleep for %d second(s)..." % (name, seconds))
yield from future
print("[%s] done!" % name)

In the previous code block, we defined the task_sleep() method annotated with @asyncio.coroutine, this method will execute the task with a specific time sleep, when execution is finished this time it will return the future.

In the next code block, we define our main program, where we define the event loop and our task list using asyncio.task.

We execute the tasks until complete with run_until_complete() method:

if __name__ == '__main__':
loop = asyncio.get_event_loop()
tasks = [asyncio.Task(task_sleep('Task-A', loop, 10)), asyncio.Task(task_sleep('Task-B', loop,5)),asyncio.Task(task_sleep('Task-C', loop))]
loop.run_until_complete(asyncio.gather(*tasks))

The following is the output of this script's execution:

[Task-A] coroutine will sleep for 10 second(s)...
[Task-B] coroutine will sleep for 5 second(s)...
[Task-C] coroutine will sleep for 1 second(s)...
[Task-C] done!
[Task-B] done!
[Task-A] done!

We can see how the first task ends with C, then B, and finally A, depending on the defined sleep times.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset