From a0384b2277b82d4eb644d588224e080c6c313801 Mon Sep 17 00:00:00 2001 From: Mattias Thall Date: Wed, 27 May 2026 02:59:41 +0200 Subject: [PATCH] Schedule auto-discovery at 4 AM daily instead of every 23 hours MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replaced the rolling 23-hour check with a fixed-time scheduler that sleeps until the next 4:00 AM, runs discovery for all users, then sleeps until the following 4 AM. No longer reads last_discovery_run — just runs at the same time every day. Co-Authored-By: Claude Sonnet 4.6 --- backend/main.py | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/backend/main.py b/backend/main.py index 4a9fd3b..610bc47 100644 --- a/backend/main.py +++ b/backend/main.py @@ -226,9 +226,15 @@ def on_startup(): from sqlalchemy import text as _text from .services.discovery import schedule_discovery, get_discovery_progress - # Wait 5 minutes after startup before the first check so the app can - # finish initialising and existing enrichment tasks can settle. - _time.sleep(300) + def _seconds_until_4am(): + now = _dt.now() + target = now.replace(hour=4, minute=0, second=0, microsecond=0) + if now >= target: + target += _td(days=1) + return (target - now).total_seconds() + + # Sleep until the next 4 AM before doing anything + _time.sleep(_seconds_until_4am()) while True: try: @@ -236,28 +242,25 @@ def on_startup(): try: rows = db.execute(_text(""" SELECT u.id AS user_id, - COALESCE(us.discovery_regions, 'US,SE') AS discovery_regions, - us.last_discovery_run + COALESCE(us.discovery_regions, 'US,SE') AS discovery_regions FROM users u LEFT JOIN user_settings us ON u.id = us.user_id """)).mappings().all() for row in rows: - last = row["last_discovery_run"] - if last is None or (_dt.utcnow() - _dt.fromisoformat(str(last))) > _td(hours=23): - uid = row["user_id"] - # Skip if a manual sweep is already running - prog = get_discovery_progress(uid) - if prog and prog.get("running"): - continue - regions = [r.strip().upper() for r in (row["discovery_regions"] or "US,SE").split(",") if r.strip()] - schedule_discovery(uid, regions) + uid = row["user_id"] + prog = get_discovery_progress(uid) + if prog and prog.get("running"): + continue + regions = [r.strip().upper() for r in (row["discovery_regions"] or "US,SE").split(",") if r.strip()] + schedule_discovery(uid, regions) finally: db.close() except Exception: pass - _time.sleep(3600) # check every hour, run if >23 h since last run + # Sleep until the next 4 AM + _time.sleep(_seconds_until_4am()) threading.Thread(target=_auto_discovery_daemon, daemon=True).start()