"""轮询定时配置,到点登录并刷新学时学分汇总。""" from __future__ import annotations import os import time from datetime import datetime from sqlalchemy import select from app.db import SessionLocal, init_db from app.models import Account, Schedule from app.service import apply_session from euniv_client import EunivClient from euniv_client.crypto import decrypt_secret def due(schedule: Schedule, now: datetime) -> bool: if not schedule.enabled: return False hour, minute = schedule.run_time.split(":") if (now.hour, now.minute) < (int(hour), int(minute)): return False if schedule.last_run_at and schedule.last_run_at.date() == now.date() and schedule.status == "ok": return False return True def run_once(client_factory=EunivClient) -> int: init_db() now = datetime.now() ran = 0 with SessionLocal() as db: schedules = list(db.scalars(select(Schedule))) for schedule in schedules: if not due(schedule, now): continue account = db.get(Account, schedule.employee_id) if account is None: schedule.status = "error" schedule.last_message = "账号不存在" db.commit() continue schedule.status = "running" db.commit() try: password = decrypt_secret(account.password_cipher) client = client_factory(account.employee_id, password) try: session = client.open_session() finally: client.close() apply_session(account, account.employee_id, password, session, now) schedule.status = "ok" schedule.last_message = "已同步学时学分" schedule.last_run_at = now ran += 1 except Exception as exc: schedule.status = "error" schedule.last_message = str(exc)[:255] schedule.last_run_at = now db.commit() return ran def main() -> None: interval = int(os.environ.get("EUNIV_WORKER_INTERVAL", "20")) while True: run_once() time.sleep(interval) if __name__ == "__main__": main()