How to Run Two Async Functions Forever in Python

Async functions, also known as coroutines, are functions that can be paused and resumed during their execution. In Python, the asyncio module provides a powerful framework for writing concurrent code using coroutines. In this article, we will explore how to run two async functions forever using different approaches in Python.

Understanding Async Functions

Async functions allow for concurrent execution of code without blocking the main thread, enabling efficient utilization of system resources. To define an async function in Python, we use the async keyword before the def statement. Within the async function, we can use the await keyword to pause execution and wait for another async function or coroutine to complete ?

import asyncio

async def example_function():
    print("Starting task")
    await asyncio.sleep(2)  # Pause for 2 seconds
    print("Task completed")

# Run the async function
asyncio.run(example_function())
Starting task
Task completed

Using asyncio.gather()

The most effective way to run two async functions forever is using asyncio.gather(). This method allows both functions to run concurrently within the same event loop ?

import asyncio

async def function1():
    count = 0
    while count < 5:  # Limited for demo
        print("Function 1")
        await asyncio.sleep(1)
        count += 1

async def function2():
    count = 0
    while count < 3:  # Limited for demo
        print("Function 2")
        await asyncio.sleep(2)
        count += 1

async def main():
    await asyncio.gather(function1(), function2())

# Run both functions concurrently
asyncio.run(main())
Function 1
Function 2
Function 1
Function 1
Function 2
Function 1
Function 1
Function 2

Using Threads for Concurrent Execution

While not truly async, threads can run functions concurrently. This approach uses the threading module to execute functions in separate threads ?

import threading
import time

def function1():
    count = 0
    while count < 3:  # Limited for demo
        print("Thread Function 1")
        time.sleep(1)
        count += 1

def function2():
    count = 0
    while count < 2:  # Limited for demo
        print("Thread Function 2")
        time.sleep(2)
        count += 1

# Create and start threads
thread1 = threading.Thread(target=function1)
thread2 = threading.Thread(target=function2)

thread1.start()
thread2.start()

# Wait for threads to complete
thread1.join()
thread2.join()
Thread Function 1
Thread Function 2
Thread Function 1
Thread Function 1
Thread Function 2

Using asyncio.create_task()

Another approach is using asyncio.create_task() to run functions as background tasks. This method provides more control over individual tasks ?

import asyncio

async def background_task1():
    count = 0
    while count < 4:  # Limited for demo
        print("Background Task 1")
        await asyncio.sleep(1.5)
        count += 1

async def background_task2():
    count = 0
    while count < 3:  # Limited for demo
        print("Background Task 2")
        await asyncio.sleep(2)
        count += 1

async def main():
    # Create tasks
    task1 = asyncio.create_task(background_task1())
    task2 = asyncio.create_task(background_task2())
    
    # Wait for both tasks to complete
    await task1
    await task2

asyncio.run(main())
Background Task 1
Background Task 2
Background Task 1
Background Task 1
Background Task 2
Background Task 1
Background Task 2

Comparison of Methods

Method Type Best For Resource Usage
asyncio.gather() Async I/O-bound tasks Low (single thread)
threading Multi-threaded Mixed workloads Medium (multiple threads)
asyncio.create_task() Async Task management Low (single thread)

Conclusion

Use asyncio.gather() for running multiple async functions concurrently in I/O-bound applications. For CPU-bound tasks or when you need true parallelism, consider threading or multiprocessing. The asyncio approach is most efficient for network operations and file I/O.

Updated on: 2026-03-27T08:40:18+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements