understanding asyncio already running forever loop and pending tasks

后端 未结 1 840
野性不改
野性不改 2021-02-09 22:10

I\'m having problems understanding how to pend a new task to an already running event loop.

This code:

import asyncio
import logging

@asyncio.coroutin         


        
1条回答
  •  伪装坚强ぢ
    2021-02-09 22:49

    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()
    

    0 讨论(0)
提交回复
热议问题