diff --git a/app/scheduler.py b/app/scheduler.py index 12ae4f0..d2314cf 100644 --- a/app/scheduler.py +++ b/app/scheduler.py @@ -15,13 +15,28 @@ def _run_all_checks(): def start_scheduler(): """Start the background scheduler. Uses interval jobs per service.""" scheduler = BackgroundScheduler() + _scheduled_ids = set() - def add_jobs(): + def sync_jobs(): + """Only add/remove jobs when the service list changes.""" + nonlocal _scheduled_ids services = get_all_services_for_scheduler() - for svc in services: - job_id = f"service_{svc['id']}" + current_ids = {svc["id"] for svc in services} + svc_by_id = {svc["id"]: svc for svc in services} + + # Remove jobs for deleted services + for sid in _scheduled_ids - current_ids: + job_id = f"service_{sid}" if scheduler.get_job(job_id): scheduler.remove_job(job_id) + _scheduled_ids.discard(sid) + + # Add jobs only for services that don't have one yet + for sid in current_ids: + if sid in _scheduled_ids: + continue + svc = svc_by_id[sid] + job_id = f"service_{sid}" interval = max(10, svc["interval_seconds"]) scheduler.add_job( run_check, @@ -30,12 +45,13 @@ def start_scheduler(): id=job_id, args=[svc["id"], svc["target"], svc["protocol"]], ) + _scheduled_ids.add(sid) # Run checks immediately on startup, then schedule _run_all_checks() - add_jobs() + sync_jobs() - # Refresh job list every 60 seconds in case services were added - scheduler.add_job(add_jobs, "interval", seconds=60, id="refresh_jobs") + # Sync job list every 60 seconds (only adds/removes when services change) + scheduler.add_job(sync_jobs, "interval", seconds=60, id="sync_jobs") scheduler.start()