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

时间:2018-04-03 05:35:16

标签: python events python-asyncio

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

# 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,因为run中的任务主要是休眠并执行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秒钟。这是一个问题,因为睡眠时间可能是几分钟。目前,我正在解决此问题,方法是将run包裹在asyncio.Task中,然后将其取消为event_loop.call_soon(the_task.cancel)

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

1 个答案:

答案 0 :(得分:6)

  

有没有办法可以在asyncio.Event上等待超时,类似于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()

这允许run几乎与使用threading.Event

async def run(self): while not await event_wait(self.stop_event, 3): pass # do stuff 完全相同
{{1}}
相关问题