In the article, we will see how to use the async & await APIs provided by asyncio for writing asynchronous code with a “fire and forget” pattern.
When do we use the fire and forget pattern?
It is particularly used when we want to launch a coroutine, but we don’t care about its result and just want to fire off the coroutine and move on to other tasks.
This is very useful when we have a long-running coroutine and we don’t want to wait for the result or when we want to perform a non-critical task.
How to use?
To use the “fire and forget” pattern in Python, simply call the coroutine with
asyncio.create_task() and this function creates a
Task object that represents the coroutine and schedules it to run on the event loop.
Once the task is scheduled, the
create_task() function returns immediately and after that, our code continues running.
Example to fire and forget pattern
import asyncio async def long_running_task(): # Perform a long-running task here await asyncio.sleep(10) print("Task complete") async def main(): # Fire and forget the long_running_task coroutine asyncio.create_task(long_running_task()) # Do other things while the task runs print("Other tasks can run while long_running_task runs") asyncio.run(main())
In the above example, to simulate the creation of long running task we have created a
long_running_task() coroutine which sleeps for 10 seconds and then prints a message “Task complete“.
The main() coroutine uses
asyncio.create_task() fires off the long_running_task() coroutine and then continues running the other code which the task runs in the background.
After running the above code, we will see the message “Other tasks can run while long_running_task runs” is printed immediately, even though the
long_running_task() takes 10 seconds to complete. This shows how the long-running task runs in the background without interrupting the main coroutine.