Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #60252 > unrolled thread

Periodic execution with asyncio

Started by"Tobias M." <tm@tobix.eu>
First post2013-11-22 22:30 +0100
Last post2013-11-22 22:30 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python


Contents

  Periodic execution with asyncio "Tobias M." <tm@tobix.eu> - 2013-11-22 22:30 +0100

#60252 — Periodic execution with asyncio

From"Tobias M." <tm@tobix.eu>
Date2013-11-22 22:30 +0100
SubjectPeriodic execution with asyncio
Message-ID<mailman.3057.1385157109.18130.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web