How it works...

In order to manage the execution of the three tasks, task_A, task_B, and task_C, we need to capture the event loop:

loop = asyncio.get_event_loop()

Then, we schedule the first call to task_A by using the call_soon construct:

end_loop = loop.time() + 60
loop.call_soon(function_1, end_loop, loop)

Let's note the definition of task_A:

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()

The asynchronous behavior of the application is determined by the following parameters:

  • time.sleep(random.randint(0, 5)): This defines the duration time of the task execution.
  • end_time: This defines the upper time limit within task_A and makes the call to task_B through the call_later method.
  • loop: This is the event loop captured previously with the get_event_loop() method.

After executing the task, loop.time is compared to end_time. If the execution time is within the maximum time (60 seconds), then the computation continues by calling task_B, otherwise, the computation ends, closing the event loop:

 if (loop.time() + 1.0) < end_time:
loop.call_later(1, task_B, end_time, loop)
else:
loop.stop()

For the other two tasks, the operations are practically the same, but only the execution time and the call to the next task vary.

Now, let me summarize the situation:

  1. task_A calls task_B with a random execution time between 1 and 5 seconds.
  2. task_B calls task_C with a random execution time between 4 and 7 seconds.
  3. task_C calls task_A with a random execution time between 6 and 10 seconds.

When the running time expires, the event loop must end:

loop.run_forever()
loop.close()

A possible output of this example would be the following:

task_A called
task_B called
task_C called
task_A called
task_B called
task_C called
task_A called
task_B called
task_C called
task_A called
task_B called
task_C called
task_A called
task_B called
task_C called
..................Content has been hidden....................

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