运行子协同程序而不阻塞父协同程序

fruv7luv  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(317)

我正在运行一个循环来侦听来自某个api的信息。当我从api得到任何响应时,我想调用一个将休眠几秒钟的子协同路由,然后处理信息并将其发送到我的电报帐户,这个子协同路由不能是非异步的。
我希望继续收听api,而不阻塞信息的处理。处理应该在后台完成。这可以通过线程实现,但我看到很多人都说,异步IO和线程在同一个位置不是一件好事。
简化的代码段:-

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).

谢谢你的调查。

tf7tbtn2

tf7tbtn21#

相当于中的“背景线程” 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 允许其他任务(包括子协同程序任务)运行的任何挂起操作。

相关问题