加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:03:33 所属栏目:Python 来源:网络整理
导读:我有一个类,其方法如下所示: # self.stop_event - threading.Eventdef run(self): while not self.stop_event.wait(3): # i.e. repeat every 3 sec pass # do stuff 这个想法是其中一些是在他们自己的线程中运行的,并且在某个时刻,一个线程执行stop_event.s
我有一个类,其方法如下所示:

# 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读