""" 平台用量定时抓取调度器 ===================== 【功能说明】 可配置的定时任务:按设定间隔自动抓取平台用量数据。 支持手动触发、停止、查看运行状态。 【技术选型理由】 1. asyncio 后台任务:无需外部调度器(APScheduler 等); 2. 配置存 SQLite:可持久化、可 API 修改; 3. 抓取用 asyncio.to_thread 包裹:Playwright 同步 API 不占用事件循环。 【实现思路】 - PlatformScheduler 单例:启动时读配置,后台循环判断是否到点; - 到点 → asyncio.to_thread(scrape_all_accounts) → 记录结果; - 配置变更 → 即时生效(重启循环)。 【潜在风险与应对】 风险1:同步抓取阻塞事件循环。 应对:asyncio.to_thread 在线程池执行同步抓取。 风险2:服务器重启后定时任务丢失。 应对:应用启动时自动恢复调度器(若配置为 enabled)。 """ from __future__ import annotations import asyncio import logging from datetime import datetime from typing import Any logger = logging.getLogger("agent.platform_scheduler") class PlatformScheduler: """平台用量定时抓取调度器""" def __init__(self) -> None: self._task: asyncio.Task | None = None self._running = False self._last_trigger: float = 0.0 def is_running(self) -> bool: """调度器是否正在运行。""" return self._running and self._task is not None and not self._task.done() async def start(self) -> dict: """启动调度器(后台循环)。""" if self.is_running(): return {"success": True, "message": "调度器已在运行"} from app.store.platform_account_store import get_platform_store store = get_platform_store() config = store.get_schedule() if not config.get("enabled"): return {"success": False, "message": "定时抓取未启用,请先在配置中开启"} self._running = True self._task = asyncio.create_task(self._loop()) logger.info("定时抓取调度器已启动(间隔 %d 分钟)", config.get("interval_minutes", 360)) return {"success": True, "message": "调度器已启动"} async def stop(self) -> dict: """停止调度器。""" self._running = False if self._task and not self._task.done(): self._task.cancel() try: await self._task except asyncio.CancelledError: pass self._task = None logger.info("定时抓取调度器已停止") return {"success": True, "message": "调度器已停止"} async def trigger_now(self) -> dict: """立即触发一次抓取(不等定时)。""" if self._last_trigger and ( datetime.now().timestamp() - self._last_trigger < 30 ): return {"success": False, "message": "30 秒内已触发过,请稍后再试"} self._last_trigger = datetime.now().timestamp() logger.info("手动触发定时抓取") result = await asyncio.to_thread(self._scrape_once) return result async def _loop(self) -> None: """后台循环:按间隔判断是否到点并执行抓取。""" from app.store.platform_account_store import get_platform_store store = get_platform_store() last_run = datetime.now().timestamp() while self._running: try: config = store.get_schedule() if not config.get("enabled"): logger.info("定时抓取已停用,调度器退出") break interval_seconds = max( 60, int(config.get("interval_minutes", 360)) * 60 ) now = datetime.now().timestamp() if now - last_run >= interval_seconds: logger.info("定时抓取触发(间隔 %d 分钟)", config["interval_minutes"]) result = await asyncio.to_thread(self._scrape_once) store.record_schedule_run(result.get("message", "")) last_run = now await asyncio.sleep(30) # 每 30 秒检查一次是否到点 except asyncio.CancelledError: break except Exception as exc: # noqa: BLE001 logger.warning("调度器循环异常:%s", exc) await asyncio.sleep(60) def _scrape_once(self) -> dict: """执行一次抓取(同步,在线程池中运行)。""" from app.services.platform_scraper import scrape_all_accounts from app.store.platform_account_store import get_platform_store store = get_platform_store() config = store.get_schedule() account_ids = config.get("account_ids", []) try: if account_ids: # 只抓指定账号 results = [] for aid in account_ids: from app.services.platform_scraper import scrape_usage r = scrape_usage(aid) results.append({"account_id": aid, **r}) else: # 抓所有激活账号 results = scrape_all_accounts() success = sum(1 for r in results if r.get("success")) message = f"定时抓取完成:成功 {success}/{len(results)}" logger.info(message) return {"success": True, "message": message, "results": results} except Exception as exc: # noqa: BLE001 message = f"定时抓取失败:{exc}" logger.warning(message) return {"success": False, "message": message} # 全局单例 _scheduler: PlatformScheduler | None = None def get_scheduler() -> PlatformScheduler: global _scheduler if _scheduler is None: _scheduler = PlatformScheduler() return _scheduler