我正在运行一个循环来侦听来自某个API的信息。当我从API得到任何响应时,我想调用一个子协同器,它会休眠几秒钟,然后处理信息并发送到我的电报帐户,这个子协同线不可能是非异步的。
我想继续听API,而不阻塞处理信息。应在后台进行处理。这可以通过线程来完成,但是我看到很多人说,Asyncio和线程在同一个地方不是一件好事。
简化的代码片段:-
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).谢谢你调查。
发布于 2021-07-08 10:48:00
与asyncio中的“后台线程”等效的是一项任务。使用asyncio.create_task在后台调度协同线的执行,并将任务暂停到完成。
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)注意,任务的await是可选的-它仍将由事件循环运行到完成。但是,父协同必须await任何挂起操作,以允许其他任务(包括子协同任务)运行。
https://stackoverflow.com/questions/68299737
复制相似问题