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