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?
Use the create_task() function of the asyncio library to create a task. Use the await keyword with the task at some point in the program so that the task can be completed before the event loop is closed by the asyncio. run() function.
Creating TasksWrap the coro coroutine into a Task and schedule its execution. Return the Task object. If name is not None , it is set as the name of the task using Task.set_name() . An optional keyword-only context argument allows specifying a custom contextvars.Context for the coro to run in.
How many times should Asyncio run () be called? It should be used as a main entry point for asyncio programs, and should ideally only be called once. New in version 3.7.
The event loop is the core of every asyncio application. Event loops run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses. Application developers should typically use the high-level asyncio functions, such as asyncio.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With