python – 等待为asyncio.Event设置超时或事件

我有一个类,其方法如下所示:

# self.stop_event -> threading.Event
def run(self):
    while not self.stop_event.wait(3):  # i.e. repeat every 3 sec
        pass  # do stuff

这个想法是其中一些是在他们自己的线程中运行的,并且在某个时刻,一个线程执行stop_event.set(),这自然会阻止所有其他线程.我想为此切换到asyncio,因为运行中的任务主要是休眠和执行IO.因此,我得:

# self.stop_event -> asyncio.Event
async def run(self):
    while not self.stop_event.is_set():
        await asyncio.sleep(3)
        pass  # do stuff

问题是asyncio.Event无法等待,因此在设置时,在方法完成之前最多等待3秒.这是一个问题,因为睡眠时间可能是几分钟.目前,我正在通过将运行包装在asyncio.Task中然后像event_loop.call_soon(the_task.cancel)一样取消它来解决这个问题.

我想问一下是否有更好的方法来实现上述目标?有没有办法我可以在asyncio.Event上等待超时,类似于threading.Event?

最佳答案

Is there a way I can wait on an asyncio.Event with a timeout somehow, similar to the threading.Event?

asyncio.wait_for可以方便地为任何协同程序添加超时.使用超时模拟threading.Event.wait可能如下所示:

async def event_wait(evt, timeout):
    try:
        await asyncio.wait_for(evt.wait(), timeout)
    except asyncio.TimeoutError:
        pass
    return evt.is_set()

这允许运行几乎与使用threading.Event的运行完全相同:

async def run(self):
    while not await event_wait(self.stop_event, 3):
        pass  # do stuff
点赞