在异步中触发并忘记任务
Fire and forget task in asyncio
在使用 Python 的 asyncio
库时,如何启动一个任务然后不关心它的完成?
例子
@asyncio.coroutine
def f():
yield From(asyncio.sleep(1))
print("world!")
@asyncio.coroutine
def g():
desired_operation(f())
print("Hello, ")
yield From(asyncio.sleep(2))
>>> loop.run_until_complete(g())
'Hello, world!'
您正在寻找 asyncio.ensure_future
(或者 asyncio.async
,如果您的 trollius
/asyncio
版本太旧而没有 ensure_future
):
from __future__ import print_function
import trollius as asyncio
from trollius import From
@asyncio.coroutine
def f():
yield From(asyncio.sleep(1))
print("world!")
@asyncio.coroutine
def g():
asyncio.ensure_future(f())
print("Hello, ", end='')
yield From(asyncio.sleep(2))
loop = asyncio.get_event_loop()
loop.run_until_complete(g())
输出:
Hello, world!
在使用 Python 的 asyncio
库时,如何启动一个任务然后不关心它的完成?
例子
@asyncio.coroutine
def f():
yield From(asyncio.sleep(1))
print("world!")
@asyncio.coroutine
def g():
desired_operation(f())
print("Hello, ")
yield From(asyncio.sleep(2))
>>> loop.run_until_complete(g())
'Hello, world!'
您正在寻找 asyncio.ensure_future
(或者 asyncio.async
,如果您的 trollius
/asyncio
版本太旧而没有 ensure_future
):
from __future__ import print_function
import trollius as asyncio
from trollius import From
@asyncio.coroutine
def f():
yield From(asyncio.sleep(1))
print("world!")
@asyncio.coroutine
def g():
asyncio.ensure_future(f())
print("Hello, ", end='')
yield From(asyncio.sleep(2))
loop = asyncio.get_event_loop()
loop.run_until_complete(g())
输出:
Hello, world!