Home > Software engineering >  python fire and forget async function in background
python fire and forget async function in background

Time:02-28

I'm trying to execute an async infinite loop function in a non blocking manner. Currently I have the following code:

class OpcuaClient():
    def __init__(self):
        ...
        #subscribe to changes
        loop = asyncio.get_event_loop()
        loop.create_task(self.subscribe_to_node(self.type_Nid))
        loop.create_task(self.subscribe_to_node(self.housingSerial_Nid))
        loop.run_forever()
 
        print("subprocesses started")
 
    async def subscribe_to_node(self, nodeid):
        async with Client(url=self.url) as client:
            node = client.get_node(nodeid)
            # subscribing to node
            sub = await client.create_subscription(500, self.handler)
            await sub.subscribe_data_change(node)
            # subscribe for infinte time
            while True:
                await asyncio.sleep(1)

however loop.run_forever() blocks the execution and "subprocess started" never gets printed. Note that i want to start the background process in the synchronous constructor. How can i achieve this ? I also tried some stuff with Multiprocessing/threading but that also failed.

CodePudding user response:

Once you start the event loop e.g. with loop_forever, it takes over the control. "Forever" means until not explicitly stopped. The following statement printing a message will be reached after the loop closes, but then everything async stops as well.

If you need to run "background" services as tasks, you need to convert your "foreground" code to an async task as well or to use multithreading or multiprocessing as you mentioned in the question, but without knowing the details about intended communication with the background tasks it is difficult to make any advice.

CodePudding user response:

Solved my issue by combining multithreading and async tasks as stated by @norbeq here.

  • Related