Home > Backend Development > Python Tutorial > How to Truly Achieve 'Fire and Forget' with Python's Async/Await?

How to Truly Achieve 'Fire and Forget' with Python's Async/Await?

Patricia Arquette
Release: 2024-11-09 01:38:02
Original
945 people have browsed it

How to Truly Achieve

"Fire and Forget" with Python's Async/Await

In Python's async/await syntax, executing an asynchronous function without awaiting it doesn't achieve the desired "fire and forget" effect. Instead, the program exits with a runtime warning.

asyncio.Task for "Fire and Forget"

To implement "fire and forget" in asyncio, use asyncio.Task to create a task that performs the desired operation in the background. By invoking asyncio.ensure_future(async_foo()), the task associated with async_foo() is started and does not wait for its completion. This is a simple yet effective approach for asynchronous operations that don't require being explicitly awaited.

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()
Copy after login

Completing Pending Tasks

Note that tasks created using asyncio.Task are expected to be completed before the event loop finishes. If tasks remain pending, a warning will be generated. To prevent this, explicitly await all pending tasks once the event loop completes.

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

    loop = asyncio.get_event_loop()
    await asyncio.gather(*asyncio.Task.all_tasks())
Copy after login

Cancelling Tasks Instead of Awaiting

Alternatively, if you don't want to await certain tasks indefinitely, you can cancel them:

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


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

    loop = asyncio.get_event_loop()
    for task in asyncio.Task.all_tasks():
        task.cancel()
        with suppress(asyncio.CancelledError):
            await task
Copy after login

The above is the detailed content of How to Truly Achieve 'Fire and Forget' with Python's Async/Await?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template