To start a coroutine from a callback, you wrap the coroutine in a Task.
That's all. E.g. (untested)
from asyncio import coroutine, get_event_loop
@coroutine
def coro():
...
yield from something()
...
# callback
def heartbeat():
get_event_loop().create_task(coro())
get_event_loop().call_later(n, heartbeat)
heartbeat() # Get it all started
On Wed, Aug 5, 2015 at 5:46 AM, Wellington Cordeiro <[email protected]>
wrote:
> I'm trying to add a system where a "heartbeat" message is sent to a server
> every n seconds by my client, but I'm having trouble with the
> loop.call_later or call_at methods. They use callbacks but I'm trying to
> run a coroutine at the set interval without blocking. The conditions I'm
> trying to work within are
>
> 1. countdown from n, when we reach zero send the heartbeat
> 2. If a message is received from the server before we hit zero, reset the
> timer
> 3. If we send a different message before we hit zero, reset the timer
>
> I'm just not sure how to implement something like this with asyncio, I
> tried using the threading.Timer class but since that creates another thread
> my client called the loop.stop() method before the interval and closed its
> connection early.
>
--
--Guido van Rossum (python.org/~guido)