Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 930
Petri Avatar asked Dec 28 '15 19:12

Petri


People also ask

How do I add a task to event loop Asyncio?

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.

How do you schedule a coroutine for execution?

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?

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.

How does the Asyncio event loop work?

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.


2 Answers

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() 
like image 59
Jashandeep Sohi Avatar answered Oct 05 '22 13:10

Jashandeep Sohi


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) 
like image 26
Dotl Avatar answered Oct 05 '22 11:10

Dotl