Are you ready to learn how to schedule tasks using asyncio in Python? Let’s dive right in and make our programs run faster than Usain Bolt on steroids (or at least close)!
First things first: import the `asyncio` module and create an event loop. This is like setting up your superhero suit before heading out to fight crime.
# Import the asyncio module to use its functions
import asyncio
# Create an event loop to manage and execute asynchronous tasks
loop = asyncio.get_event_loop() # This function returns the current event loop or creates a new one if none exists
# The following code will be executed within the event loop
async def main():
# Define a coroutine function to be executed asynchronously
print("Hello") # Print statement to display "Hello" on the console
await asyncio.sleep(1) # Asynchronously pause the execution for 1 second
print("World") # Print statement to display "World" on the console
# Schedule the execution of the coroutine function within the event loop
loop.run_until_complete(main()) # This function runs the event loop until the coroutine is complete
# Close the event loop to prevent any further execution
loop.close() # This function closes the event loop and frees any resources used by it
Now that we have our event loop, let’s schedule some tasks! We can do this using the `asyncio.ensure_future()` function or by creating tasks and passing them to `asyncio.gather()`.
For example:
# Import the asyncio library
import asyncio
# Get the event loop
loop = asyncio.get_event_loop()
# Define a function for task1
def task1():
print("Task 1 started")
# Define an async function for task2
async def task2():
print("Task 2 started")
# Define an async function for the main task
async def main():
# Create a list of tasks to be scheduled
tasks = [task1(), task2()] # Schedule both tasks at once!
# Use asyncio.gather() to schedule the tasks and wait for them to complete
await asyncio.gather(*tasks)
# Print a message when the main task is finished
print("Main function finished")
# Check if the script is being run directly
if __name__ == '__main__':
# Run the event loop until the main task is complete
loop.run_until_complete(main())
# Output:
# Task 1 started
# Task 2 started
# Main function finished
# Explanation:
# The script starts by importing the asyncio library and getting the event loop.
# Then, a function is defined for task1, which simply prints a message.
# An async function is also defined for task2, which also prints a message.
# Next, an async function is defined for the main task, which creates a list of tasks to be scheduled and uses asyncio.gather() to schedule them and wait for them to complete.
# Finally, the script checks if it is being run directly and runs the event loop until the main task is complete.
# The output shows that both tasks were scheduled and completed before the main function finished.
In the above example, we’re scheduling two tasks called `task1()` and `task2()`. Both of these tasks will run concurrently with our main function and print “Task 1 started” and “Task 2 started”, respectively. Once both tasks are done, they stop the event loop using `loop.stop()`, which means that any other tasks scheduled after this one won’t be executed.
But what if we want to schedule multiple tasks at once? No problem! We can use a list comprehension and pass all of them into `asyncio.gather()`. This is like calling in backup for an entire team of superheroes instead of just one.
For example:
# Import the asyncio library to enable asynchronous programming
import asyncio
# Get the event loop for the current thread
loop = asyncio.get_event_loop()
# Define a function for task1
def task1():
print("Task 1 started")
# Define an asynchronous function for task2
async def task2():
print("Task 2 started")
# Define the main function
async def main():
# Create a list of tasks to be executed
tasks = [task1(), task2()] # Schedule both tasks at once!
# Use asyncio.gather() to schedule and run all tasks in the list concurrently
await asyncio.gather(*tasks)
# Print a message to indicate that the main function has finished
print("Main function finished")
# Check if the current module is being run as the main program
if __name__ == '__main__':
# Run the event loop until all tasks are complete
loop.run_until_complete(main())
# Output:
# Task 1 started
# Task 2 started
# Main function finished
# Explanation:
# The script starts by importing the asyncio library and getting the event loop for the current thread.
# Next, the script defines a function for task1 and an asynchronous function for task2.
# Then, the main function is defined, which will be the entry point for the script.
# Inside the main function, a list of tasks is created, containing both task1 and task2.
# The asyncio.gather() function is used to schedule and run all tasks in the list concurrently.
# Finally, the event loop is run until all tasks are complete, and a message is printed to indicate that the main function has finished.
# This allows for multiple tasks to be scheduled and executed at once, improving efficiency and performance.
In the above example, we’re scheduling two tasks called `task1()` and `task2()`. Both of these tasks will run concurrently with our main function and print “Task 1 started” and “Task 2 started”, respectively. Once both tasks are done, they stop the event loop using `loop.stop()`, which means that any other tasks scheduled after this one won’t be executed.
Using tasks is like manually scheduling functions on the event loop since in this case, the tasks shall be tracked by the event loop. This allows us to write asynchronous code and handle concurrent tasks over an event loop.
For more patterns that we can use with asyncio, check out @ambv’s series about asyncio best practices on discuss-python.org. These patterns will help you build really great applications with asyncio!