How to run two async functions forever in Python?

There are different programming techniques, one programming technique called Asynchronous programming is a type of programming where we execute the same task with more than one task without blocking the Main task (function).

In Python, there are many ways to execute more than one function concurrently, one of the ways is by using asyncio. Async programming allows you to write concurrent code that runs in a single thread.

Please Remember: Asyncio doesn’t use threads or multiprocessing to make the program Asynchronous.

Coroutine: Coroutines are a general control structure whereby flow control is cooperatively passed between two different routines without returning.

In asyncio Coroutine can be created by using async keyword before def.

async def speak_async():
   for i in range(100):
       print("Hello Welcome To LingarajTechhub")

And if you run the above async function directly you will get a runtime warning.

RuntimeWarning: coroutine ‘speak_async’ was never awaited

speak_async()

To run an async function (coroutine) you have to call it using an Event Loop.

Event Loops: Suppose when you think of Event Loop as functions to run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses. 

Example 1: Event Loop example to run async Function to run a single async function:

import asyncio


async def function_asyc():
	for i in range(5):
		print("Hello, I'm Lingaraj")
		print("LingarajTechhub is Great")
	return 0

# to run the above function we'll
# use Event Loops these are low
# level functions to run async functions
loop = asyncio.get_event_loop()
loop.run_until_complete(function_asyc())
loop.close()
print("HELLO WORLD")
print("HELLO WORLD")

# You can also use High Level functions Like:
# asyncio.run(function_asyc())

Output:

Hello, I'm Lingaraj
LingarajTechhub is Great
Hello, I'm Lingaraj
LingarajTechhub is Great
Hello, I'm Lingaraj
LingarajTechhub is Great
Hello, I'm Lingaraj
LingarajTechhub is Great
Hello, I'm Lingaraj
LingarajTechhub is Great
HELLO WORLD
HELLO WORLD

Example 2: Execute more than one function at a time. To do so we have to create a new async function (main) and call all the async functions (which we want to run at the same time) in that new function (main). And then call the new (main) function using Event Loop.

import asyncio


async def function_asyc():
	for i in range(100000):
		if i % 50000 == 0:
			print("Hello, I'm Lingaraj")
			print("LingarajTechhub is Great")
	return 0

async def function_2():
	print("\n HELLO WORLD \n")
	return 0

async def main():
	f1 = loop.create_task(function_asyc())
	f2 = loop.create_task(function_2())
	await asyncio.wait([f1, f2])

# to run the above function we'll
# use Event Loops these are low
# level functions to run async functions
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

# You can also use High Level functions Like:
# asyncio.run(function_asyc())

Output:

Hello, I'm Lingaraj
LingarajTechhub is Great
Hello, I'm Lingaraj
LingarajTechhub is Great

 HELLO WORLD 

Note: .create_task() is used to run multiple async functions at a time.

Example 3: Here you can see function_async() and function_2() are not running concurrently, the output of function_async() is displayed first and then the output of function_2() is displayed, that means function_2() is being executed after the execution of function_async().

But we don’t want that! we want both functions to make progress concurrently, so to achieve that in python we have to explicitly tell the computer when to shift from one function to another.

import asyncio


async def function_asyc():
	
	for i in range(100000):
		if i % 50000 == 0:
			print("Hello, I'm Lingaraj")
			print("LingarajTechhub is Great")
			
			# New Line Added
			await asyncio.sleep(0.01)
	return 0

async def function_2():
	print("\n HELLO WORLD \n")
	return 0

async def main():
	f1 = loop.create_task(function_asyc())
	f2 = loop.create_task(function_2())
	await asyncio.wait([f1, f2])

# to run the above function we'll
# use Event Loops these are low level
# functions to run async functions
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

# You can also use High Level functions Like:
# asyncio.run(function_asyc())

Output:

Hello, I'm Lingaraj
LingarajTechhub is Great

 HELLO WORLD 

Hello, I'm Lingaraj
LingarajTechhub is Great

Now as you can see, the second function is executed during the execution of the running function (function_async()). So these were the basics now let’s see how to run two async functions forever.

Running two async functions forever Python:

Method 1: Just use the while True loop in the main function:

import asyncio


async def function_asyc():
	i = 0
	while i < 1000000:
		i += 1
		if i % 50000 == 0:
			print("Hello, I'm Lingaraj")
			print("LingarajTechhub is Great")
			await asyncio.sleep(0.01)

async def function_2():
	print("\n HELLO WORLD \n")


async def main():
	
	# New Line Added
	while True:
		f1 = loop.create_task(function_asyc())
		f2 = loop.create_task(function_2())
		await asyncio.wait([f1, f2])

# to run the above function we'll
# use Event Loops these are low
# level functions to run async functions
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

Output:

Hello, I'm Lingaraj
LingarajTechhub is Great

 HELLO WORLD 

Hello, I'm Lingaraj
LingarajTechhub is Great
Hello, I'm Lingaraj
LingarajTechhub is Great
Hello, I'm Lingaraj
LingarajTechhub is Great
Hello, I'm Lingaraj
LingarajTechhub is Great
Hello, I'm Lingaraj
LingarajTechhub is Great
Hello, I'm Lingaraj
LingarajTechhub is Great
Hello, I'm Lingaraj
LingarajTechhub is Great
.
.
.
.

Method 2: Using while True loops for both functions and calling them using asyncio.ensure_future() and loop.run_forever() 

Note: ensure_future lets us execute a coroutine in the background, without explicitly waiting for it to finish.

import asyncio


async def function_asyc():
	i = 0
	
	while True:
		i += 1
		if i % 50000 == 0:
			print("Hello, I'm Lingaraj")
			print("LingarajTechhub is Great")
			await asyncio.sleep(0.01)

async def function_2():
	while True:
		await asyncio.sleep(0.01)
		print("\n HELLO WORLD \n")

loop = asyncio.get_event_loop()
asyncio.ensure_future(function_asyc())
asyncio.ensure_future(function_2())
loop.run_forever()

Output:

Hello, I'm Lingaraj
LingarajTechhub is Great
Hello, I'm Lingaraj
LingarajTechhub is Great

 HELLO WORLD 

Hello, I'm Lingaraj
LingarajTechhub is Great
.
.
.

Please comment and share this post if you find helpful and wants to improve WhatsApp us.

Default image
Lingaraj Senapati
Hey There! I am Lingaraj Senapati, the Co-founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.
Articles: 217

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply