how to add a coroutine to a running asyncio loop?
You can use create_task
for scheduling new coroutines:
import asyncio
async def cor1():
...
async def cor2():
...
async def main(loop):
await asyncio.sleep(0)
t1 = loop.create_task(cor1())
await cor2()
await t1
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
loop.close()
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)