如何轮询python asyncio任务状态

时间:2017-07-20 22:38:00

标签: python python-asyncio gevent

使用gevent,我可以像这样监视一个长时间运行的函数:

    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执行此操作?我尝试过以下但是我被卡住了:

    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()

我如何更改此内容以获得预期的行为?

1 个答案:

答案 0 :(得分:4)

您可以使用ensure_future安排长时间运行的任务(但不等待它)。作为回报,您将获得一个Future对象,其done方法类似于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()