在不阻止父协同程序的情况下运行子协同程序

2024-06-10 02:33:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行一个循环来侦听来自某个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).

谢谢你的调查


Tags: importloopapiasyncio信息路由asyncdef
1条回答
网友
1楼 · 发布于 2024-06-10 02:33:40

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任何挂起操作以允许其他任务(包括子协同程序任务)运行

相关问题 更多 >