Search code examples
pythonasynchronousclientopc-ua

python fire and forget async function in background


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.


Solution

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