how to add a coroutine to a running asyncio loop?

后端 未结 4 1181
慢半拍i
慢半拍i 2020-12-23 16:20

How can one add a new coroutine to a running asyncio loop? Ie. one that is already executing a set of coroutines.

I guess as a workaround one could wait for existing

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-23 17:06

    To add a function to an already running event loop you can use:

    asyncio.ensure_future(my_coro())

    In my case I was using multithreading (threading) alongside asyncio and wanted to add a task to the event loop that was already running. For anyone else in the same situation, be sure to explicitly state the event loop (as one doesn't exist inside a Thread). i.e:

    In global scope:

    event_loop = asyncio.get_event_loop()
    

    Then later, inside your Thread:

    asyncio.ensure_future(my_coro(), loop=event_loop)
    

提交回复
热议问题