Files
syops/backend/app/services/schedule/web_scanner.py
T

64 lines
2.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/app/services/schedule/web_scanner.py
用途:Web 进程内的排程扫描兜底线程——让开发环境(只跑 run.py,没有独立 schedule-worker
容器)也能按 cron 触发到期排程(如订单交期回复每天 07:00 的 ERP 全量同步)。
依赖:app.jobs.runner.run_forever、app.jobs.store.claim_next(schedule 队列)、JobContext。
逻辑:create_app 启动时按 SCHEDULE_WEB_SCANNER_ENABLED 决定是否拉起守护线程;线程内
推送 app context 后复用与 workers/worker_scheduler.py 完全相同的消费路径
(claim_next('schedule') → prepare_schedule_queue 扫描到期任务 → handler 执行)。
多进程并发安全由 enqueue_due_schedule_runs 的 FOR UPDATE SKIP LOCKED 与
schedule_runs 活动 run 去重保证,与独立 worker 并存不会重复执行。
生产环境默认关闭(compose 已有 hxops-schedule-worker 专职容器),可用环境变量覆盖。
"""
from __future__ import annotations
import threading
_web_scanner_started = False
_web_scanner_lock = threading.Lock()
def start_web_schedule_scanner(app) -> None:
"""
按配置在 Web 进程内启动排程扫描守护线程(幂等;重复调用直接返回)。
用途与触发时机:create_app 启动阶段调用;AI/请求路径不触发。
开发环境默认开启(SCHEDULE_WEB_SCANNER_ENABLED 缺省 true),
生产环境默认关闭(缺省 false,由 hxops-schedule-worker 容器负责)。
核心逻辑:[STEP 1] 读 SCHEDULE_WEB_SCANNER_ENABLED,关闭则不打扰;
[STEP 2] 进程内单例锁后起 daemon 线程,线程内推送 app context、
导入 handlers、复用 run_forever(queues=['schedule']) 主循环。
"""
global _web_scanner_started
enabled = bool(app.config.get("SCHEDULE_WEB_SCANNER_ENABLED", False))
if not enabled:
app.logger.info("Web schedule scanner disabled by SCHEDULE_WEB_SCANNER_ENABLED=false")
return
with _web_scanner_lock:
if _web_scanner_started:
return
def _loop(app_ref=app):
with app_ref.app_context():
import app.jobs.handlers # noqa: F401 — 触发 @register_handler
from app.jobs.context import JobContext
from app.jobs.runner import run_forever
ctx = JobContext(
config=dict(app_ref.config),
logger=app_ref.logger,
extras={"queues": ["schedule"]},
)
app_ref.logger.info("Web schedule scanner starting (queues=['schedule'])")
run_forever(ctx)
thread = threading.Thread(target=_loop, name="web-schedule-scanner", daemon=True)
thread.start()
_web_scanner_started = True
app.logger.info("Web schedule scanner started")