Files
syops/backend/app/jobs/runner.py
T

56 lines
2.0 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/jobs/runner.py
用途:Worker 主循环 poll → dispatch → ack/fail。
逻辑:worker.py 调用 run_forever(ctx);claim 走 store,执行走 registry handler。
"""
from __future__ import annotations
import time
from typing import TYPE_CHECKING
from app.jobs import store
from app.jobs.registry import get_handler
if TYPE_CHECKING:
from app.jobs.context import JobContext
def _resolve_poll_seconds(ctx: JobContext) -> float:
"""按队列配置读取轮询间隔。"""
queues = ctx.extras.get('queues') or ['kb']
if 'shipping' in queues and 'kb' not in queues:
return float(ctx.config.get('SHIPPING_NOTICE_WORKER_POLL_SECONDS', 2))
return float(ctx.config.get('KB_WORKER_POLL_SECONDS', 2))
def run_forever(ctx: JobContext, *, poll_interval_seconds: float | None = None) -> None:
"""
持续轮询并执行任务。
核心逻辑:claim_next → get_handler → handler(ctx, payload);异常时 mark_failed。
Args:
ctx: Worker 上下文(extras.queues 指定消费队列)。
poll_interval_seconds: 无任务时的休眠秒数;默认按队列读 config。
"""
queues = ctx.extras.get('queues') or ['kb']
poll = poll_interval_seconds if poll_interval_seconds is not None else _resolve_poll_seconds(ctx)
ctx.logger.info('Job runner started queues=%s poll_seconds=%s', queues, poll)
while True:
job = store.claim_next(queues=queues)
if not job:
time.sleep(poll)
continue
handler = get_handler(job['job_type'])
if not handler:
ctx.logger.error('No handler for job_type=%s job_id=%s', job.get('job_type'), job.get('id'))
store.mark_failed(job['id'], message=f'no handler for {job.get("job_type")}')
continue
try:
handler(ctx, job.get('payload') or {})
except Exception as exc:
ctx.logger.exception('Handler failed job_id=%s', job.get('id'))
store.mark_failed(job['id'], message=str(exc))