Files
DecomEval/backend/app/runtime.py
T

66 lines
1.8 KiB
Python

"""凭证刷新和采集周期。用户任务由队列或本进程线程执行。"""
from __future__ import annotations
import asyncio
import logging
import threading
import time
from app.config import installed
from app.db import session_scope
from app.tasks.runner import refresh_accounts, scan_sources
logger = logging.getLogger("decom")
_started = False
def start_background(owner: str = "api") -> None:
global _started
if _started:
return
_started = True
threading.Thread(target=_refresh_loop, args=(owner,), name="decom-refresh", daemon=True).start()
threading.Thread(target=_collect_loop, args=(owner,), name="decom-collect", daemon=True).start()
def _owns_schedule(owner: str) -> bool:
from app.config import inline_worker
try:
inline = inline_worker()
except Exception:
return False
return inline if owner == "api" else not inline
def _refresh_loop(owner: str) -> None:
while True:
if not installed() or not _owns_schedule(owner):
time.sleep(2)
continue
seconds = 300
try:
with session_scope() as session:
from app.models import AppSetting
setting = session.get(AppSetting, 1)
if setting is not None:
seconds = setting.credential_refresh_seconds
asyncio.run(refresh_accounts())
except Exception as exc:
logger.info("凭证刷新未完成: %s", exc)
time.sleep(max(60, seconds))
def _collect_loop(owner: str) -> None:
while True:
if not installed() or not _owns_schedule(owner):
time.sleep(2)
continue
try:
scan_sources()
except Exception as exc:
logger.info("采集调度未完成: %s", exc)
time.sleep(60)