"""Background collection scheduler.""" from __future__ import annotations import asyncio import time import traceback from typing import Dict, List, Optional from . import capacity, db, registry class Scheduler: def __init__(self, interval: int = 20) -> None: self.interval = interval self.task: Optional[asyncio.Task] = None self.last_prune = 0.0 self.last_tick_ms: Optional[int] = None self.last_error: Optional[str] = None self.runs = 0 async def start(self) -> None: if self.task is None: self.task = asyncio.create_task(self._loop()) async def stop(self) -> None: if self.task: self.task.cancel() try: await self.task except asyncio.CancelledError: pass self.task = None async def _loop(self) -> None: await asyncio.sleep(2) while True: try: await asyncio.to_thread(self.tick) self.last_error = None except asyncio.CancelledError: raise except Exception as exc: self.last_error = f"{type(exc).__name__}: {exc}" print(f"[headroom] scheduler error: {self.last_error}\n{traceback.format_exc()}", flush=True) await asyncio.sleep(self.interval) def tick(self) -> None: started = time.time() if time.time() - self.last_prune > 6 * 3600: removed = capacity.prune_samples() self.last_prune = time.time() if removed: print(f"[headroom] retention pruned {removed} samples", flush=True) due = registry.due_modules() ran = 0 errors = 0 for module in due: try: registry.run_module(module["id"], trigger="scheduler") self.runs += 1 ran += 1 except Exception as exc: errors += 1 print(f"[headroom] module {module['id']} failed: {exc}", flush=True) if ran or errors: capacity.evaluate_policies() self.last_tick_ms = int((time.time() - started) * 1000) def stats(self) -> Dict[str, object]: return { "running": bool(self.task and not self.task.done()), "interval_seconds": self.interval, "last_tick_ms": self.last_tick_ms, "last_error": self.last_error, "runs": self.runs, } scheduler = Scheduler()