Home > database >  Print message while a function is running in Python with AsyncIO
Print message while a function is running in Python with AsyncIO

Time:02-16

I'm trying to create a print function that keeps printing, for example, 'Hello World', while another function (called miner) is running in parallel, and both functions must end at the same time.

enter image description here

This is for a real-time cost measurer for bitcoin mining that I'm working on.

I found that python as asyncio and tried to use it, however I couldn't get the print function to stop at the same time the miner function ends. The timer function printed once and waited for the miner function.

enter image description here

import asyncio
import time  
from datetime import datetime
class Test2:  
    async def miner(self):
        await asyncio.sleep(5)
        return 0
    async def timer(self):  
        while True:
            print("\n Hello World \n")
            time.sleep(1)

t2 = Test2()
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(t2.miner(), t2.timer()))

I tried concurrent tasks, but both function does not run in parallel (timer and miner). Could you show me a way to solve this? Thank you!

CodePudding user response:

You can also use threading:-


def func1():
    print('Working')

def func2():
    print("Working")

if __name__ == '__main__':
    Thread(target = func1).start()
    Thread(target = func2).start()

CodePudding user response:

  1. time.sleep() is not asynchronous function so timer process locks other operations before it ends (but unfortunately it is endless)
  2. You may add shared trigger variable to stop timer when miner complete
import asyncio

class Test2:

    is_ended = False

    async def miner(self):
        await asyncio.sleep(5)
        self.is_ended = True
        print("\n I'm done \n")
        return 0

    async def timer(self):  
        while True:
            if self.is_ended:
               print('\n Bye Bye \n')
               break
            print("\n Hello World \n")
            await asyncio.sleep(1)

t2 = Test2()
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(t2.miner(), t2.timer()))

 Hello World 


 Hello World 


 Hello World 


 Hello World 


 Hello World 


 I'm done 


 Bye Bye 

  • Related