Home >Backend Development >Python Tutorial >How to Truly Achieve 'Fire and Forget' with Python's Async/Await?
"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()
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())
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
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!