如何轮询python asyncio任务状态 [英] How to poll python asyncio task status
本文介绍了如何轮询python asyncio任务状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用gevent,我可以像这样监视长时间运行的功能:
With gevent, i can monitor a long running function like so:
greenlet = gevent.Greenlet(long_running_task, *args, **kwargs)
greenlet.start()
while not greenlet.ready():
send_heartbeat()
gevent.sleep(heartbeat_interval)
if greenlet.successful():
send_success(greenlet.value)
else:
send_failure(exception=greenlet.exception)
我该如何使用asyncio?我尝试了以下方法,但遇到了麻烦:
How would I do this with asyncio? I've tried the following but I'm stuck:
loop = asyncio.get_event_loop()
async def send_heartbeat(heartbeat_interval=15):
send_heartbeat()
asyncio.sleep(heartbeat_interval)
await asyncio.sleep(1)
loop.run_until_complete(asyncio.wait([long_running_task(*args, **kwargs), send_heartbeat()]))
loop.close()
我将如何更改它以获得预期的行为?
How would I change this to get the intended behavior?
推荐答案
You can schedule the long running task with ensure_future
(but not awaiting it). In return you'll get a Future object that have done
method that is similar to ready
async def some_job():
future = asyncio.ensure_future(long_running_task(*args, **kwargs))
while not future.done():
await send_heartbeat(heartbeat_interval=15)
try:
result = future.result()
except asyncio.CancelledError:
# the task has been cancelled
except Exception:
# some exception was raised in long running task
loop = asyncio.get_event_loop()
loop.run_until_complete(some_job())
loop.close()
这篇关于如何轮询python asyncio任务状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文