Async/await provides a convenient syntax for asynchronous programming in Python. However, there are situations where we want to initiate an asynchronous operation without waiting for its completion. This is often referred to as "fire and forget."
Python provides asyncio.Task, which allows us to create a task that will execute in the background. Using asyncio.Task, we can achieve "fire and forget" by adding the following code to our script:
import asyncio async def async_foo(): # Do some asynchronous stuff here # Create a task for async_foo() asyncio.ensure_future(async_foo())
This creates a task for async_foo() that will execute asynchronously without blocking the main thread.
If our script completes before all tasks are finished, we can use the following code to await all pending tasks:
pending_tasks = asyncio.Task.all_tasks() loop.run_until_complete(asyncio.gather(*pending_tasks))
This ensures that all tasks have completed before the script exits, preventing any warnings or errors.
In some cases, we may not want to wait for tasks to complete. We can cancel them using the following code:
for task in pending_tasks: task.cancel() with suppress(asyncio.CancelledError): loop.run_until_complete(task)
This cancels the tasks and suppresses any errors that may be raised as a result of the cancellation.
위 내용은 Python에서 Async/Await를 사용하여 'Fire and Forget'을 어떻게 달성할 수 있나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!