pythonpython-3.xasynchronouspython-asyncio

how to add a coroutine to a running asyncio loop?


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 coroutines to complete and then initialize a new loop (with the additional coroutine). But is there a better way?


Solution

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