how to add a coroutine to a running asyncio loop?

Petri picture Petri · Dec 28, 2015 · Viewed 39.2k times · Source

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?

Answer

Jashandeep Sohi picture Jashandeep Sohi · Dec 28, 2015

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