How to Run Two Async Functions Forever - Python
Last Updated :
12 Apr, 2025
In Python, asynchronous programming allows us to run multiple tasks concurrently without blocking the main program. The most common way to handle async tasks in Python is through the asyncio library.
Key Concepts
- Coroutines: Functions that we define using the async keyword. These functions allow us to pause their execution using await so that other tasks can run.
- Event Loop: This controls the execution of asynchronous tasks. The event loop runs tasks in the background, switching between them when one is paused to let others run.
- asyncio.sleep(): This allows us to simulate asynchronous operations like waiting for a network request or I/O operations . It lets other tasks run during the wait.
Example:
Python
import asyncio
async def fun():
for i in range(5):
print("Hello, I’m running")
await asyncio.sleep(1)
asyncio.run(fun())
Output
Using asyncio Explanation: This code defines an asynchronous function fun() that prints "Hello, I’m running" five times, with a 1-second delay between each print using await asyncio.sleep(1). The asyncio.run(fun()) call runs the function in an event loop.
Running two async functions simultaneously
If we want to run multiple async functions at once, we can use asyncio.create_task() to schedule them for execution and await to let the event loop manage them. Here's how to run two functions concurrently.
Python
import asyncio
async def fun1():
while True:
print("Function 1 is running")
await asyncio.sleep(0.5)
async def fun2():
while True:
print("Function 2 is running")
await asyncio.sleep(0.5)
async def main():
await asyncio.gather(asyncio.create_task(fun1()), asyncio.create_task(fun2()))
asyncio.run(main())
Output
Using asyncio.create_task()Explanation: This code defines two async functions fun1() and fun2(), that print a message every 0.5 seconds in infinite loops. The main() function uses asyncio.gather() to run both functions concurrently. asyncio.run(main()) starts the event loop to execute both functions asynchronously.
Running async functions forever
To run two async functions forever, we can use an infinite loop in our main function or use asyncio.ensure_future() along with loop.run_forever(). By placing the while True loop inside an async function, we ensure that the function continuously executes its code, such as printing messages or performing tasks, without stopping. The await asyncio.sleep() call allows the function to pause without blocking other tasks.
Python
import asyncio
async def fun1():
i = 0
while True:
i += 1
if i % 5 == 0:
print("Function 1: Running asynchronously...")
await asyncio.sleep(1)
async def fun2():
while True:
print("Function 2: Running asynchronously...")
await asyncio.sleep(1)
async def main():
await asyncio.gather(asyncio.create_task(fun1()), asyncio.create_task(fun2()))
asyncio.run(main())
Output
Using whileExplanation: This code defines two async functions, fun1() and fun2(), which run indefinitely, printing messages every second. fun1() prints every 5th iteration. Both functions use await asyncio.sleep(1) to pause without blocking. asyncio.gather() runs both functions concurrently and asyncio.run(main()) starts the event loop.
How to run two async functions forever - Python - FAQs
How to run two async functions at once in Python?
Use asyncio.gather()
to run multiple asynchronous functions concurrently. Here’s how:
import asyncio
async def first_function():
# your code here
await asyncio.sleep(1)
async def second_function():
# your code here
await asyncio.sleep(1)
async def main():
await asyncio.gather(first_function(), second_function())
asyncio.run(main())
How to run an async function multiple times in Python?
To run an async function multiple times concurrently, call it multiple times inside asyncio.gather()
:
import asyncio
async def async_task():
# your code here
await asyncio.sleep(1)
async def main():
await asyncio.gather(*(async_task() for _ in range(5)))
asyncio.run(main())
How to make a function asynchronous in Python?
Prefix the function definition with async def
and use await
for asynchronous operations within it:
import asyncio
async def async_function():
await asyncio.sleep(1) # Example of an async operation
How to start an async function in Python?
To start an asynchronous function, use asyncio.run()
which automatically creates and manages the event loop:
import asyncio
async def start_async_function():
await asyncio.sleep(1) # your async operation here
asyncio.run(start_async_function())
How to run the same program multiple times in Python?
To run the entire program or a specific part multiple times, you can use a simple loop. For parallel execution, consider using the multiprocessing
module:
import multiprocessing
def function_to_run():
print("Function is running")
if __name__ == "__main__":
processes = [multiprocessing.Process(target=function_to_run) for _ in range(5)]
for process in processes:
process.start()
for process in processes:
process.join()