Periodic execution with asyncio

Tobias M. tm at tobix.eu
Fri Nov 22 16:30:26 EST 2013


Hello guys,

I am using the asyncio package (Codename 'Tulip'), which will be 
available in Python 3.4, for the first time.
I want the event loop to run a function periodically (e.g. every 2 
seconds). PEP 3156 suggests two ways to implement such a periodic call:

1. Using a callback that reschedules itself, using call_later().
2. Using a coroutine containing a loop and a sleep() call.

I implemented the first approach in a class with an easy to use 
interface. It can be subclassed and the run() method
can be overwritten to provide the code that will be called periodically. 
The interval is specified in the constructor and the task can be started 
and stopped:


import asyncio

class PeriodicTask(object):

     def __init__(self, interval):
         self._interval = interval
         self._loop = asyncio.get_event_loop()

     def _run(self):
         self.run()
         self._handler = self._loop.call_later(self._interval, self._run)

     def run(self):
         print('Hello World')

     def start(self):
         self._handler = self._loop.call_later(self._interval, self._run)

     def stop(self):
         self._handler.cancel()


To run this task and execute run() every 2 seconds you can do:

task = PeriodicTask(2)
task.start()
asyncio.get_event_loop().run_forever()


So far, this works for me. But as I have no experience with asynchronous 
IO I have two questions:

1. Is this a reasonable implementation or is there anything to improve?

2. How would you implement the second approach from the PEP (using a 
coroutine) with the same interface as my PeriodicTask above?

I tried the second approach but wasn't able to come up with a solution, 
as I was too confused by the concepts of coroutines, Tasks, etc.

Regards,
Tobias





More information about the Python-list mailing list