Schedule auto-discovery at 4 AM daily instead of every 23 hours

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 <noreply@anthropic.com>
This commit is contained in:
2026-05-27 02:59:41 +02:00
parent bcbd552eab
commit a0384b2277

View File

@@ -226,9 +226,15 @@ def on_startup():
from sqlalchemy import text as _text from sqlalchemy import text as _text
from .services.discovery import schedule_discovery, get_discovery_progress from .services.discovery import schedule_discovery, get_discovery_progress
# Wait 5 minutes after startup before the first check so the app can def _seconds_until_4am():
# finish initialising and existing enrichment tasks can settle. now = _dt.now()
_time.sleep(300) 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: while True:
try: try:
@@ -236,28 +242,25 @@ def on_startup():
try: try:
rows = db.execute(_text(""" rows = db.execute(_text("""
SELECT u.id AS user_id, SELECT u.id AS user_id,
COALESCE(us.discovery_regions, 'US,SE') AS discovery_regions, COALESCE(us.discovery_regions, 'US,SE') AS discovery_regions
us.last_discovery_run
FROM users u FROM users u
LEFT JOIN user_settings us ON u.id = us.user_id LEFT JOIN user_settings us ON u.id = us.user_id
""")).mappings().all() """)).mappings().all()
for row in rows: for row in rows:
last = row["last_discovery_run"] uid = row["user_id"]
if last is None or (_dt.utcnow() - _dt.fromisoformat(str(last))) > _td(hours=23): prog = get_discovery_progress(uid)
uid = row["user_id"] if prog and prog.get("running"):
# Skip if a manual sweep is already running continue
prog = get_discovery_progress(uid) regions = [r.strip().upper() for r in (row["discovery_regions"] or "US,SE").split(",") if r.strip()]
if prog and prog.get("running"): schedule_discovery(uid, regions)
continue
regions = [r.strip().upper() for r in (row["discovery_regions"] or "US,SE").split(",") if r.strip()]
schedule_discovery(uid, regions)
finally: finally:
db.close() db.close()
except Exception: except Exception:
pass 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() threading.Thread(target=_auto_discovery_daemon, daemon=True).start()