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()