import asyncio from app.config import settings from app.services.dashboard_monitor import run_dashboard_monitor_cycle _stop_event: asyncio.Event | None = None _worker_task: asyncio.Task | None = None async def _loop() -> None: assert _stop_event is not None while not _stop_event.is_set(): try: await run_dashboard_monitor_cycle(run_type="auto", scope=None, force=False) except Exception as exc: print(f"[dashboard_monitor] Cycle error: {exc}") try: await asyncio.wait_for(_stop_event.wait(), timeout=settings.DASHBOARD_MONITOR_TICK_SECONDS) except asyncio.TimeoutError: pass def start_dashboard_monitor() -> None: global _stop_event, _worker_task _stop_event = asyncio.Event() _worker_task = asyncio.create_task(_loop()) print("[dashboard_monitor] Worker started") async def stop_dashboard_monitor() -> None: global _stop_event, _worker_task if _stop_event: _stop_event.set() if _worker_task: _worker_task.cancel() try: await _worker_task except asyncio.CancelledError: pass print("[dashboard_monitor] Worker stopped")