This is my first attempt at using asyncio
in a project. I'd like my class to initialize and run, with several of its functions running periodically "in the background". I'd like the class' init to return after starting these background tasks, so that it can continue to do its synchronous stuff at the same time.
What I have:
class MyClass(threading.Thread):
def __init__(self, param):
self.stoprequest = threading.Event()
threading.Thread.__init__(self)
self.param = param
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
asyncio.ensure_future(self.periodic(), loop=self.loop)
print("Initialized")
async def periodic(self):
while True:
print("I'm here")
await asyncio.sleep(1)
def run(self):
# continue to do synchronous things
I'm sure unsurprisingly, this doesn't work. I've also tried using a "normal" asyncio
function with run_until_complete()
in init, but of course init never returns then.
How can I run asyncio
functions that belong to this class periodically in the background, while the rest of the class (run()
) continues to do synchronous work?