I have a program that needs to run multiple independent tasks. I need a way to start them and then stop them when an event occur
I've defined a base class like this
class InterruptibleTask:
def __init__(self, stop_evt=None):
self.stop_evt = stop_evt or asyncio.Event()
async def init(self):
pass
async def cleanup(self):
pass
async def run(self):
await self.init()
await self.stop_evt.wait()
await self.cleanup()
async def stop(self):
self.stop_evt.set()
class MyFirstTask(InterruptibleTask):
async def do_work(self):
while not self.stop_evt.is_set:
print("Do Work")
asyncio.sleep(1)
async def init(self):
await asyncio.create_task(self.do_work())
class MysecondTask(InterruptibleTask):
async def do_work(self):
while not self.stop_evt.is_set:
print("Do 2nd Work")
asyncio.sleep(3)
async def init(self):
await asyncio.create_task(self.do_work())
STOP = asyncio.Event()
tasks = [MyFirstTask(STOP), MysecondTask(STOP)]
async def run_tasks():
await asyncio.gather(*tasks)
def stop_tasks():
for task in tasks:
task.stop()
try
asyncio.run(run_tasks())
except KeyboardInterrupt:
pass
finally:
stop_tasks()
It this the right approach? Do you have any example? How can I stop all taks and subtask on exit?