How to do it...

In this example, we look at how to use the event loop statements provided by the asyncio library, in order to build an application that works in asynchronous mode. 

In this example, we defined three tasks. Each task has an execution time determined by a time random parameter. Once the execution is finished, Task A calls Task B, Task B calls Task C, and Task C calls Task A.

The event loop will continue until a termination condition is met. As we can imagine, this example follows this asynchronous schema:

 Asynchronous programming model

Let's have a look at the following steps:

  1. Let's start by importing the libraries needed for our implementation:
import asyncio
import time
import random
  1. Then, we define task_A, whose execution time is determined randomly and can vary from 1 to 5 seconds. At the end of the execution, if the termination condition is not satisfied, then the computation goes to task_B:
def task_A(end_time, loop):
print ("task_A called")
time.sleep(random.randint(0, 5))
if (loop.time() + 1.0) < end_time:
loop.call_later(1, task_B, end_time, loop)
else:
loop.stop()

  1. Here, task_B is defined. Its execution time is determined randomly and can vary from 4 to 7 seconds. At the end of the execution, if the termination condition is not satisfied, then the computation goes to task_B:
def task_B(end_time, loop):
print ("task_B called ")
time.sleep(random.randint(3, 7))
if (loop.time() + 1.0) < end_time:
loop.call_later(1, task_C, end_time, loop)
else:
loop.stop()
  1. Then, task_C is implemented. Its execution time is determined randomly and can vary from 6 to 10 seconds. At the end of the execution, if the termination condition is not satisfied, then the computation goes back to task_A:
def task_C(end_time, loop):
print ("task_C called")
time.sleep(random.randint(5, 10))
if (loop.time() + 1.0) < end_time:
loop.call_later(1, task_A, end_time, loop)
else:
loop.stop()
  1. The next statement defines the loop parameter, which simply gets the current event loop:
loop = asyncio.get_event_loop()
  1. The end_loop value defines the termination condition. The execution of this example code must last 60 seconds:
end_loop = loop.time() + 60
  1. Then, let's request the execution of task_A:
loop.call_soon(task_A, end_loop, loop)
  1. Now, we set a long duration cycle that continues to respond to events until it is stopped:
loop.run_forever()
  1. Now, close the event loop:
loop.close()

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

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