Running asynchronous Python functions with different time delays
Write a Python program that creates three asynchronous functions and displays their respective names with different delays (1 second, 2 seconds, and 3 seconds).
Sample Solution:
Code:
import asyncio
async def display_name_with_delay(name, delay):
await asyncio.sleep(delay)
print(name)
async def main():
tasks = [
display_name_with_delay("Asyn. function-1", 1),
display_name_with_delay("Asyn. function-2", 2),
display_name_with_delay("Asyn. function-3", 3)
]
await asyncio.gather(*tasks)
# Run the event loop
asyncio.run(main())
Output:
Asyn. function-1 Asyn. function-2 Asyn. function-3
Explanation:
In the above exercise,
- "display_name_with_delay()" is an asynchronous function that takes a 'name' and a 'delay' as arguments. It uses await asyncio.sleep(delay) to introduce the specified delay, and then displays the given name.
- The main coroutine runs the three asynchronous functions concurrently using the asyncio.gather() function. It creates a list of tasks representing each call to print_name_with_delay.
- The asyncio.run(main()) line starts the event loop, which runs the concurrent tasks defined in the tasks list.
When you run this program, you'll see the names "Asyn. function-1", "Asyn. function-2", "Asyn. function-3" displayed on the console with delays of 1 second, 2 seconds, and 3 seconds respectively.
Flowchart:
Previous: Delaying Print Output with asyncio Coroutines in Python.
Next: Printing numbers with a delay using asyncio coroutines in Python.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics