Skip to content
Advertisement

Run a Child Coroutine without Blocking Parent Coroutine

I’m running a Loop to listening information from some API. When I get any response from the API, I want to call a child coroutine that will sleep for few seconds, then process the Information and send it to my Telegram Account, this child coroutine can’t be non-async.

I want to keep listening to the API, without blocking for processing the Information. Processing should be done in the background. This could be done by Threading, but I’ve seen many people say, Asyncio and Threading in the same place is not a good thing.

A Simplified Code Snippet :-

JavaScript

Thanks for looking into it.

Advertisement

Answer

The equivalent to a “background Thread” in asyncio is a task. Use asyncio.create_task to schedule execution of a coroutine in the background, and await the task to pause until completion.

JavaScript

Note that awaiting the task is optional – it will still be run to completion by the event loop. However, the parent coroutine must await any suspending action to allow other tasks (including the child coroutine task) to run.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement