Open In App

How to run two async functions forever – Python

Last Updated : 17 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Asynchronous programming is a type of programming in which we can execute 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.

Note: 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 I'm Abhishek, writer on GFG")

If you try to run an 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: You can 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:

Python3




import asyncio
  
  
async def function_asyc():
    for i in range(5):
        print("Hello, I'm Abhishek")
        print("GFG 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 Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG 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 Loops…

Code:

Python3




import asyncio
  
  
async def function_asyc():
    for i in range(100000):
        if i % 50000 == 0:
            print("Hello, I'm Abhishek")
            print("GFG 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 Abhishek
GFG is Great
Hello, I'm Abhishek
GFG 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.

Code:

Python3




import asyncio
  
  
async def function_asyc():
    
    for i in range(100000):
        if i % 50000 == 0:
            print("Hello, I'm Abhishek")
            print("GFG 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 Abhishek
GFG is Great

 HELLO WORLD 

Hello, I'm Abhishek
GFG 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:

Python3




import asyncio
  
  
async def function_asyc():
    i = 0
    while i < 1000000:
        i += 1
        if i % 50000 == 0:
            print("Hello, I'm Abhishek")
            print("GFG 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 Abhishek
GFG is Great

 HELLO WORLD 

Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG 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.

Python3




import asyncio
  
  
async def function_asyc():
    i = 0
      
    while True:
        i += 1
        if i % 50000 == 0:
            print("Hello, I'm Abhishek")
            print("GFG 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 Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great

 HELLO WORLD 

Hello, I'm Abhishek
GFG is Great
.
.
.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads