MRocklin
MRocklin

Reputation: 57301

Fire and forget task in asyncio

When using Python's asyncio library, how can I fire off a task and then not care about its completion?

Example

@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!'

Upvotes: 3

Views: 2319

Answers (1)

dano
dano

Reputation: 94951

You're looking for asyncio.ensure_future (or asyncio.async if your version of trollius/asyncio is too old to have 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())

Output:

Hello, world!

Upvotes: 3

Related Questions