【发布时间】:2017-12-07 02:06:29
【问题描述】:
在我的async 处理程序中,我想等到任务的状态发生变化。现在,我只是在无限循环中检查状态并等待。下面是一个例子,wait_until_done 函数:
import asyncio
class LongTask:
state = 'PENDING'
my_task = LongTask()
def done():
my_task.state = 'DONE'
async def wait_until_done():
while True:
if my_task.state == 'PENDING':
await asyncio.sleep(2)
else:
break
print("Finally, the task is done")
def main(loop, *args, **kwargs):
asyncio.ensure_future(wait_until_done())
loop.call_later(delay=5, callback=done)
loop = asyncio.get_event_loop()
main(loop)
loop.run_forever()
有没有更好的方法来做到这一点?
【问题讨论】:
-
观察者模式可能是您想要使用的。使对象“可观察”,然后将处理程序注册为对象的观察者,因此当状态更改时,它将调用您想要的任何方法。 stackoverflow.com/questions/1904351/…
标签: python python-3.5 python-asyncio