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 :-
import asyncio import time loop = asyncio.get_event_loop() async def ParentProcess(): async def ChildProcess(sleep): await asyncio.sleep(sleep) print("Slept", sleep, "Sec(s).") await ScheduleCheck() for i in range(5): print("Continue") await ChildProcess(5) print("Continue") loop.run_until_complete(ParentProcess()) # Expected Output :- # Continue # Continue # Slept 5 Sec(s).
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.
while True: async for i in stream(): print("Continue") # spawn task in the background background_task = asyncio.create_task(ChildProcess(5)) print("Continue") # wait for task to complete await background_task await asyncio.sleep(2)
Note that await
ing 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.