Iva*_*hev 4 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
Run Code Online (Sandbox Code Playgroud)
这个想法是,其中一些是在他们自己的线程中运行的,并且在某个时刻,一个线程会运行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
Run Code Online (Sandbox Code Playgroud)
问题是asyncio.Event无法等待,因此在设置时,在方法完成之前最多等待3秒钟.这是一个问题,因为睡眠时间可能是几分钟.目前,我正在解决这个问题,run包括一个asyncio.Task然后取消它event_loop.call_soon(the_task.cancel).
我想问一下是否有更好的方法来实现上述目标?有没有办法我可以在asyncio.Event某种程度上等待超时,类似于threading.Event?
use*_*342 11
有没有办法我可以在
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 Code Online (Sandbox Code Playgroud)
这允许run几乎完全像使用的那个threading.Event:
async def run(self):
while not await event_wait(self.stop_event, 3):
pass # do stuff
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1507 次 |
| 最近记录: |