from app_class import AppClass from config import Config from trigger import Trigger import asyncio from asyncio import Task class TriggerScheduler(AppClass): def __init__(self, _config: Config) -> None: super().__init__(_config) self.tasks: list[Task] = [] async def trigger(self, _trigger: Trigger) -> None: """Run a trigger with a specific name at a given interval.""" while True: self.log.info("Trigger %s is running", _trigger.name) _trigger.run() await asyncio.sleep(_trigger.config.interval_in_seconds) def start_trigger(self, _trigger: Trigger) -> None: """Start a new trigger.""" task = asyncio.create_task(self.trigger(_trigger)) self.tasks.append(task) async def stop_triggers(self) -> None: """Stop all triggers.""" for task in self.tasks: task.cancel() await asyncio.gather(*self.tasks, return_exceptions=True) async def run(self) -> None: """Run the scheduler and keep it alive until stopped.""" try: while True: await asyncio.sleep(1) # Keep the main function alive except asyncio.exceptions.CancelledError: self.log.info("Exiting, stopping all triggers") await self.stop_triggers()