scheduler.py
5.51 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# -*- coding: utf-8 -*-
"""
定时调度器模块
================
功能:定时扫描 PROCESSING 状态的任务,自动调用 DataProcessor 进行处理。
特点:
- 支持通过配置文件调整执行间隔
- 使用互斥锁防止并发执行
- 提供 start() / stop() 生命周期管理
- 提供状态查询接口
作者:数据处理引擎
"""
import threading
import logging
import sys
import traceback
from datetime import datetime
from config import Config
logger = logging.getLogger('TaskScheduler')
# 注册线程异常钩子,捕获 daemon 线程中的未处理异常
def _threading_excepthook(args):
"""捕获线程中未处理的异常并记录完整堆栈。"""
error_msg = f"线程异常: {args.exc_type.__name__}: {args.exc_value}\n"
error_msg += ''.join(traceback.format_exception(args.exc_type, args.exc_value, args.exc_traceback))
logger.error(error_msg)
sys.stderr.write(error_msg)
sys.stderr.flush()
threading.excepthook = _threading_excepthook
class TaskScheduler:
"""
数据处理定时调度器。
周期性扫描 data_process_task 表中 status='PROCESSING' 的任务,
调用 DataProcessor.process_all() 执行清洗入库。
"""
def __init__(self, app=None):
"""
初始化调度器。
参数:
- app: Flask app 实例(用于获取数据库上下文)
"""
self.app = app
self._scheduler = None
self._lock = threading.Lock()
self._running = False
self._is_processing = False
self._last_run_time = None
self._last_run_result = None
def start(self):
"""
启动定时调度器。
若 APScheduler 未安装,则使用 threading.Timer 作为后备方案。
"""
if self._running:
logger.warning("[调度器] 已在运行中,忽略 start() 调用")
return
if not Config.SCHEDULER_ENABLED:
logger.info("[调度器] 定时任务未启用 (SCHEDULER_ENABLED=false),跳过启动")
return
interval = Config.SCHEDULER_INTERVAL_SECONDS
try:
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
self._scheduler = BackgroundScheduler(daemon=True)
self._scheduler.add_job(
self._execute_scan,
trigger=IntervalTrigger(seconds=interval),
id='data_process_scan',
name='数据处理任务扫描',
replace_existing=True,
)
self._scheduler.start()
self._running = True
logger.info(f"[调度器] APScheduler 已启动,执行间隔: {interval}秒")
except ImportError:
logger.warning("[调度器] APScheduler 未安装,使用 threading 后备方案")
self._running = True
self._thread_timer(interval)
except Exception as e:
logger.error(f"[调度器] 启动失败: {str(e)}")
raise
def stop(self):
"""
停止定时调度器。
"""
if not self._running:
return
self._running = False
if self._scheduler:
try:
self._scheduler.shutdown(wait=False)
logger.info("[调度器] APScheduler 已停止")
except Exception as e:
logger.error(f"[调度器] 停止 APScheduler 时出错: {str(e)}")
logger.info("[调度器] 调度器已完全停止")
def get_status(self):
"""
获取调度器当前状态。
返回: dict,包含运行状态、上次执行时间等信息
"""
return {
'enabled': Config.SCHEDULER_ENABLED,
'running': self._running,
'interval_seconds': Config.SCHEDULER_INTERVAL_SECONDS,
'is_processing': self._is_processing,
'last_run_time': self._last_run_time.strftime('%Y-%m-%d %H:%M:%S') if self._last_run_time else None,
'last_run_result': self._last_run_result,
}
def _thread_timer(self, interval):
"""
threading 后备方案:使用 Timer 实现定时循环。
"""
if not self._running:
return
self._execute_scan()
if self._running:
timer = threading.Timer(interval, self._thread_timer, args=[interval])
timer.daemon = True
timer.start()
def _execute_scan(self):
"""
执行扫描处理任务。
使用互斥锁防止并发执行。
"""
if not self._lock.acquire(blocking=False):
logger.debug("[调度器] 上一轮处理尚未完成,跳过本轮扫描")
return
self._is_processing = True
self._last_run_time = datetime.now()
try:
logger.info("[调度器] 开始扫描 PROCESSING 任务...")
with self.app.app_context():
from processor import DataProcessor
processor = DataProcessor(app=self.app)
result = processor.process_all()
self._last_run_result = result
logger.info(f"[调度器] 扫描完成:成功 {result.get('success', 0)} 个,失败 {result.get('failed', 0)} 个")
except Exception as e:
logger.error(f"[调度器] 扫描执行异常: {str(e)}")
self._last_run_result = {'error': str(e)}
finally:
self._is_processing = False
self._lock.release()