如何使用asyncio计划​​和取消任务

时间:2016-10-13 08:56:57

标签: python python-asyncio

我正在编写客户端 - 服务器应用程序。连接时,客户端向服务器发送心跳"心跳"例如,信号每秒。 在服务器端,我需要一种机制,我可以在其中添加异步执行的任务(或协程或其他)。此外,当我停止发送"心跳"信号。

换句话说,当服务器启动任务时,它会有超时或 ttl ,例如3秒。当服务器收到"心跳"信号将计时器重置另外3秒,直到任务完成或客户端断开连接(停止发送信号)。

这是从pymotw.com上的 asyncio 教程取消任务的example。但是这里的任务在event_loop开始之前被取消了,这对我来说并不合适。

import asyncio

async def task_func():
    print('in task_func')
    return 'the result'


event_loop = asyncio.get_event_loop()
try:
    print('creating task')
    task = event_loop.create_task(task_func())

    print('canceling task')
    task.cancel()

    print('entering event loop')
    event_loop.run_until_complete(task)
    print('task: {!r}'.format(task))
except asyncio.CancelledError:
    print('caught error from cancelled task')
else:
    print('task result: {!r}'.format(task.result()))
finally:
    event_loop.close()

1 个答案:

答案 0 :(得分:10)

您可以使用asyncio Task包装器通过ensure_future()方法执行任务。

ensure_future会自动将您的协程包装在Task包装器中,并将其附加到您的事件循环中。然后,Task包装器还将确保协程从awaitawait语句(或直到协程完成)'曲柄翻转'。

换句话说,只需将常规协程传递给ensure_future,并将结果Task对象分配给变量。然后,您可以在需要停止时拨打Task.cancel()

import asyncio

async def task_func():
    print('in task_func')
    # if the task needs to run for a while you'll need an await statement
    # to provide a pause point so that other coroutines can run in the mean time
    await some_db_or_long_running_background_coroutine()
    # or if this is a once-off thing, then return the result,
    # but then you don't really need a Task wrapper...
    # return 'the result'

async def my_app():
    my_task = None
    while True:
        await asyncio.sleep(0)

        # listen for trigger / heartbeat
        if heartbeat and not my_task:
            my_task = asyncio.ensure_future(task_func())

        # also listen for termination of hearbeat / connection
        elif not heartbeat and my_task:
            if not my_task.cancelled():
                my_task.cancel()
            else:
                my_task = None

run_app = asyncio.ensure_future(my_app())
event_loop = asyncio.get_event_loop()
event_loop.run_forever()

请注意,任务适用于长时间运行的任务,这些任务需要在后台继续工作而不会中断主流。如果您只需要一个快速的一次性方法,那么只需直接调用该函数即可。