- Picked, Python, Python-Functions

How to run two async functions forever – Python

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 awaitedspeak_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:Python3import asyncio    async def function_asyc():    for i in range(5):        print(“Hello, I’m Abhishek”)        print(“GFG is Great”)    return 0  loop = asyncio.get_event_loop()loop.run_until_complete(function_asyc())loop.close()print(“HELLO WORLD”)print(“HELLO WORLD”)  OutputHello, 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 WORLDExample 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:Python3import 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])  loop = asyncio.get_event_loop()loop.run_until_complete(main())loop.close()  OutputHello, 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:Python3import asyncio    async def function_asyc():        for i in range(100000):        if i % 50000 == 0:            print(“Hello, I’m Abhishek”)            print(“GFG is Great”)                                      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])  loop = asyncio.get_event_loop()loop.run_until_complete(main())loop.close()  OutputHello, I’m Abhishek
GFG is Great

HELLO WORLD

Hello, I’m Abhishek
GFG is GreatNow 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:Python3import 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():            while True:        f1 = loop.create_task(function_asyc())        f2 = loop.create_task(function_2())        await asyncio.wait([f1, f2])  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.Python3import 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 . . . Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course