Issue
I'm having problems understanding how to pend a new task to an already running event loop.
This code:
import asyncio
import logging
@asyncio.coroutine
def blocking(cmd):
while True:
logging.info("in blocking coroutine")
yield from asyncio.sleep(0.01)
print("ping")
def main():
logging.info("in main funciton")
loop = asyncio.get_event_loop()
logging.info("new loop created")
logging.info("loop running forever")
loop.run_forever()
asyncio.async(blocking("ls"))
logging.basicConfig(level = logging.INFO)
main()
Changing run_forever()
to run_until_complete(asyncio.async(blocking("ls"))
works fine. But I'm really confused - why I can't pend a task on the already running loop?
Solution
The problem is that the call to loop.run_forever()
blocks; it starts the event loop, and won't return until you explicitly stop the loop - hence the forever
part of run_forever
. Your program never explicitly stops the event loop, so your asyncio.async(blocking("ls"))
call is never reached.
Using asyncio.async
to add a new task to an already running loop is fine, you just need to make sure the function is actually called from inside a coroutine or callback inside the event loop. Here are some examples:
Schedule blocking
to run as soon as the event loop starts:
def main():
logging.info("in main funciton")
loop = asyncio.get_event_loop()
logging.info("new loop created")
logging.info("loop running forever")
asyncio.async(blocking("ls"))
loop.run_forever()
Schedule blocking
from a callback executed by the event loop:
def start_blocking():
asyncio.async(blocking("ls"))
def main():
logging.info("in main funciton")
loop = asyncio.get_event_loop()
logging.info("new loop created")
logging.info("loop running forever")
loop.call_soon(start_blocking) # Calls start_blocking once the event loop starts
loop.run_forever()
Answered By - dano
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.