"Fire and forget" python async/await

"Fire and forget" python async/await

有时需要进行一些非关键的异步操作,但我不想等待它完成。在 Tornado 的协程实现中,您可以通过简单地省略 yield 关键字来 "fire & forget" 一个异步函数。

我一直在尝试弄清楚如何 "fire & forget" 使用 Python 3.5 中发布的新 async/await 语法。例如,一个简化的代码片段:

async def async_foo():
    print("Do some stuff asynchronously here...")

def bar():
    async_foo()  # fire and forget "async_foo()"

bar()

虽然 bar() 永远不会执行,但我们会收到运行时警告:

RuntimeWarning: coroutine 'async_foo' was never awaited
  async_foo()  # fire and forget "async_foo()"

这不完全是异步执行,但也许run_in_executor()适合你。

def fire_and_forget(task, *args, **kwargs):
    loop = asyncio.get_event_loop()
    if callable(task):
        return loop.run_in_executor(None, task, *args, **kwargs)
    else:    
        raise TypeError('Task must be a callable')

def foo():
    #asynchronous stuff here


fire_and_forget(foo)

更新:

如果您使用 Python,请将 asyncio.ensure_future 替换为 asyncio.create_task >= 3.7 这是一种更新、更好的方式 to spawn tasks


asyncio.Task 到“即发即忘”

根据 python 文档,asyncio.Task it is possible to start some coroutine to execute "in the background". The task created by asyncio.ensure_future 不会阻止执行(因此该函数将立即 return!)。这看起来像是一种按照您的要求“即发即弃”的方式。

import asyncio


async def async_foo():
    print("async_foo started")
    await asyncio.sleep(1)
    print("async_foo done")


async def main():
    asyncio.ensure_future(async_foo())  # fire and forget async_foo()

    # btw, you can also create tasks inside non-async funcs

    print('Do some actions 1')
    await asyncio.sleep(1)
    print('Do some actions 2')
    await asyncio.sleep(1)
    print('Do some actions 3')


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

输出:

Do some actions 1
async_foo started
Do some actions 2
async_foo done
Do some actions 3

如果任务在事件循环完成后执行怎么办?

请注意,asyncio 期望任务在事件循环完成时完成。因此,如果您将 main() 更改为:

async def main():
    asyncio.ensure_future(async_foo())  # fire and forget

    print('Do some actions 1')
    await asyncio.sleep(0.1)
    print('Do some actions 2')

程序完成后您将收到此警告:

Task was destroyed but it is pending!
task: <Task pending coro=<async_foo() running at [...]

为了防止这种情况,您可以在事件循环完成后

async def main():
    asyncio.ensure_future(async_foo())  # fire and forget

    print('Do some actions 1')
    await asyncio.sleep(0.1)
    print('Do some actions 2')


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    
    # Let's also finish all running tasks:
    pending = asyncio.Task.all_tasks()
    loop.run_until_complete(asyncio.gather(*pending))

终止任务而不是等待它们

有时您不想等待任务完成(例如,某些任务可能会永远 运行 创建)。在这种情况下,您可以 cancel() 他们而不是等待他们:

import asyncio
from contextlib import suppress


async def echo_forever():
    while True:
        print("echo")
        await asyncio.sleep(1)


async def main():
    asyncio.ensure_future(echo_forever())  # fire and forget

    print('Do some actions 1')
    await asyncio.sleep(1)
    print('Do some actions 2')
    await asyncio.sleep(1)
    print('Do some actions 3')


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

    # Let's also cancel all running tasks:
    pending = asyncio.Task.all_tasks()
    for task in pending:
        task.cancel()
        # Now we should await task to execute it's cancellation.
        # Cancelled task raises asyncio.CancelledError that we can suppress:
        with suppress(asyncio.CancelledError):
            loop.run_until_complete(task)

输出:

Do some actions 1
echo
Do some actions 2
echo
Do some actions 3
echo

输出:

>>> Hello
>>> foo() started
>>> I didn't wait for foo()
>>> foo() completed

这是一个简单的修饰函数,它将执行推到后台,控制线移动到代码的下一行。

主要优点是,您不必将函数声明为 await

import asyncio
import time

def fire_and_forget(f):
    def wrapped(*args, **kwargs):
        return asyncio.get_event_loop().run_in_executor(None, f, *args, *kwargs)

    return wrapped

@fire_and_forget
def foo():
    print("foo() started")
    time.sleep(1)
    print("foo() completed")

print("Hello")
foo()
print("I didn't wait for foo()")

注意:检查我的另一个 ,它使用没有 asyncio 的普通 thread 做同样的事情。

出于某种原因,如果您无法使用 asyncio,那么这里是使用普通线程的实现。检查我的其他答案和谢尔盖的答案。

import threading, time

def fire_and_forget(f):
    def wrapped():
        threading.Thread(target=f).start()

    return wrapped

@fire_and_forget
def foo():
    print("foo() started")
    time.sleep(1)
    print("foo() completed")

print("Hello")
foo()
print("I didn't wait for foo()")

生产

>>> Hello
>>> foo() started
>>> I didn't wait for foo()
>>> foo() completed
def fire_and_forget(f):
    def wrapped(*args, **kwargs):
        threading.Thread(target=functools.partial(f, *args, **kwargs)).start()

    return wrapped

是上面的更好的版本——不使用 asyncio