我正在运行一个循环来监听来自某个 API 的信息。当我从 API 得到任何响应时,我想调用一个会休眠几秒钟的子协程,然后处理信息并将其发送到我的 Telegram 帐户,这个子协程不能是非异步的。
我想继续收听 API,而不阻止处理信息。 处理应在后台完成。这可以通过Threading来完成,但我看到很多人说,Asyncio和Threading放在一起不是什么好事。
一个简化的代码片段:-
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).
感谢您的调查。
答案 0 :(得分:1)
相当于 asyncio
中的“后台线程”是一个任务。使用 asyncio.create_task
在后台安排协程的执行,并使用 await
暂停任务直到完成。
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
任何挂起操作才能允许其他任务(包括子协程任务)运行。