scheduler.py
2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
from __future__ import annotations
import logging
from apscheduler.events import EVENT_JOB_ERROR, EVENT_JOB_EXECUTED, JobExecutionEvent
from apscheduler.schedulers.blocking import BlockingScheduler
from app.config.loader import ConfigLoader
from app.jobs.log_context import JOB_NAME_MAP
from app.jobs.runner import run_job
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s - %(message)s",
)
logger = logging.getLogger(__name__)
DEFAULT_JOB_SPECS = [
{"job_key": "sync_wecom_bots_groups_messages", "minutes": 2},
{"job_key": "sync_customer_groups", "minutes": 10},
{"job_key": "dispatch_customer_group_messages", "minutes": 1},
]
def _job_listener(event: JobExecutionEvent) -> None:
if event.exception:
logger.error(
"Scheduler job failed: job_id=%s task=%s exception=%s",
event.job_id,
JOB_NAME_MAP.get(str(event.job_id), str(event.job_id)),
event.exception,
)
else:
logger.info(
"Scheduler job executed: job_id=%s task=%s",
event.job_id,
JOB_NAME_MAP.get(str(event.job_id), str(event.job_id)),
)
def load_job_specs() -> list[dict[str, int | str]]:
settings = ConfigLoader().load_settings()
specs: list[dict[str, int | str]] = []
for default_spec in DEFAULT_JOB_SPECS:
job_key = str(default_spec["job_key"])
minutes = default_spec["minutes"]
job_settings = settings.scheduler.jobs.get(job_key)
if job_settings is not None:
minutes = job_settings.minutes
specs.append({"job_key": job_key, "minutes": minutes})
return specs
def build_scheduler() -> BlockingScheduler:
scheduler = BlockingScheduler(timezone="Asia/Shanghai")
job_specs = load_job_specs()
for spec in job_specs:
scheduler.add_job(
run_job,
"interval",
minutes=spec["minutes"],
args=[spec["job_key"]],
id=spec["job_key"],
replace_existing=True,
max_instances=1,
coalesce=True,
)
scheduler.add_listener(_job_listener, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)
return scheduler
def main() -> None:
job_specs = load_job_specs()
scheduler = build_scheduler()
logger.info("APScheduler starting,当前将注册 3 类任务:同步机器人与客户群消息 / 同步一客一群建群编排 / 分发客户群消息到下游")
for spec in job_specs:
logger.info(
"Registered job: job_key=%s task=%s interval_minutes=%s",
spec["job_key"],
JOB_NAME_MAP.get(str(spec["job_key"]), str(spec["job_key"])),
spec["minutes"],
)
scheduler.start()
if __name__ == "__main__":
main()