Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #60259
| From | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| Subject | Re: Periodic execution with asyncio |
| Date | 2013-11-22 20:33 -0500 |
| References | <528FCCF2.4020608@tobix.eu> <l6or6b$aao$1@ger.gmane.org> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3063.1385170405.18130.python-list@python.org> (permalink) |
On 11/22/2013 7:00 PM, Terry Reedy wrote:
> On 11/22/2013 4:30 PM, Tobias M. wrote:
[snip callback versions by Tobias and me]
>> 2. How would you implement the second approach from the PEP (using a
>> coroutine) with the same interface as my PeriodicTask above?
>
> Theoretically, by Guido's rationale, that should be easier (for me, at
> least), since it would be more like the kind of Python code I already
> write.
>
>> 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.
>
> I will try to look at the PEP and see how it works for me.
I was initially baffled also until I managed to assemble all the needed
pieces.
import asyncio
def f():
print('Hello World')
@asyncio.coroutine
def g(func, interval):
while True:
yield from asyncio.sleep(interval)
func()
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(asyncio.Task(g(f, 2)))
except KeyboardInterrupt:
print('Loop stopped')
I think Guido's point is that async generator version is quite similar
to the 'normal' synchronous version.
import time
def f():
print('Hello World')
def h(func, interval):
while True:
time.sleep(interval)
func()
try:
h(f, 2))
except KeyboardInterrupt:
print('Loop stopped')
--
Terry Jan Reedy
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Periodic execution with asyncio Terry Reedy <tjreedy@udel.edu> - 2013-11-22 20:33 -0500
csiph-web