django-autojob 2.0.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
autojob/__init__.py ADDED
File without changes
autojob/admin.py ADDED
@@ -0,0 +1,198 @@
1
+ import os
2
+
3
+ from apscheduler.jobstores.base import ConflictingIdError
4
+ from django import forms
5
+ from django.contrib import admin
6
+ from django.utils import timezone
7
+
8
+ from autojob.cmd_listener import publish_cmd
9
+ from autojob.job_new import JobAction, load_job_func, parse_job_rate
10
+
11
+ from .models import JobList, JobTrigger
12
+ import logging
13
+ from django.contrib import messages
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ class JobListForm(forms.ModelForm):
19
+ """保存任务时校验执行频率,规则复用 job_new。"""
20
+
21
+ class Meta:
22
+ model = JobList
23
+ fields = '__all__'
24
+
25
+ def clean(self):
26
+ cleaned_data = super().clean()
27
+ action_type = cleaned_data.get('action_type')
28
+ job_rate = cleaned_data.get('job_rate')
29
+ if action_type and job_rate:
30
+ try:
31
+ parse_job_rate(action_type, job_rate)
32
+ except ValueError as exc:
33
+ self.add_error('job_rate', str(exc))
34
+ return cleaned_data
35
+
36
+
37
+ class JobTriggerForm(forms.ModelForm):
38
+ """保存触发器时校验触发器路径可解析、可导入。"""
39
+
40
+ class Meta:
41
+ model = JobTrigger
42
+ fields = '__all__'
43
+
44
+ def clean_func_path(self):
45
+ func_path = self.cleaned_data.get('func_path', '').strip()
46
+ try:
47
+ load_job_func(func_path)
48
+ except ValueError as exc:
49
+ raise forms.ValidationError(str(exc))
50
+ return func_path
51
+
52
+
53
+ # Register your models here.
54
+ @admin.register(JobTrigger)
55
+ class JobTriggerAdmin(admin.ModelAdmin):
56
+ form = JobTriggerForm
57
+ list_display = ('id', 'trigger_name', 'trigger_func', 'func_path', 'description')
58
+ list_display_links = ('id', 'trigger_name')
59
+ list_per_page = 20
60
+ list_max_show_all = 7
61
+ ordering = ('id',)
62
+
63
+
64
+ # Register your models here.
65
+ @admin.register(JobList)
66
+ class JobListAdmin(admin.ModelAdmin):
67
+ form = JobListForm
68
+ list_display = ('id', 'job_name', 'job_state', 'action_type', 'job_rate', 'update_time')
69
+ list_display_links = ('id', 'job_name')
70
+ list_filter = ('job_state',)
71
+ list_editable = ('action_type', 'job_rate',)
72
+ list_per_page = 20
73
+ list_max_show_all = 7
74
+ ordering = ('-job_state', 'id',)
75
+ actions = ['start_job', 'stop_job', 'action_job']
76
+
77
+ def get_readonly_fields(self, request, obj=None):
78
+ if obj:
79
+ readonly_fields = ('trigger_id', 'job_state', 'update_time',)
80
+ else:
81
+ readonly_fields = ('job_state',)
82
+ return readonly_fields
83
+
84
+ def get_changelist_form(self, request, **kwargs):
85
+ # 列表页的 action_type / job_rate 内联编辑同样要走执行频率校验
86
+ kwargs.setdefault('form', JobListForm)
87
+ return super().get_changelist_form(request, **kwargs)
88
+
89
+ def save_model(self, request, obj, form, change):
90
+ super().save_model(request, obj, form, change)
91
+ if obj.job_state == 1 and obj.trigger_id:
92
+ # 保存成功后再广播给所有 worker,避免保存失败时已发出指令
93
+ publish_cmd('modify', obj.trigger.trigger_func + '-' + str(obj.id),
94
+ (obj.action_type, obj.job_rate))
95
+
96
+ def start_job(self, request, queryset):
97
+ global job_name
98
+ trigger_list = queryset.values('trigger_id')
99
+ rate_list = queryset.values('job_rate')
100
+ id_list = queryset.values('id')
101
+ job_num = len(id_list)
102
+ name_list = queryset.values('job_name')
103
+ action_type = queryset.values('action_type')
104
+ current_time = timezone.now()
105
+ for (trigger, rate, id_, name, type_) in zip(trigger_list, rate_list, id_list, name_list, action_type):
106
+ try:
107
+ job_name = name.get('job_name')
108
+ job_rate = rate.get('job_rate')
109
+ job_id = id_.get('id')
110
+ trigger_name = JobList.objects.get(id=job_id).trigger.trigger_func
111
+ job_type = type_.get('action_type')
112
+ if hasattr(JobAction, 'start_%s_job' % job_type):
113
+ logger.info('发布 %s 指令 %s', 'start', {'op': 'start', 'job_id': job_id})
114
+ func = getattr(JobAction, 'start_%s_job' % job_type)
115
+ func(trigger_name, job_rate, str(job_id))
116
+ queryset.filter(id=job_id).update(job_state=1, update_time=current_time)
117
+ logger.info('%s 指令执行完成: %s, worker_pid=%s', 'start', job_id, os.getpid())
118
+ else:
119
+ messages.error(request, '【启动错误】 ' + job_name + ' 任务不存在!')
120
+ job_num -= 1
121
+ except ConflictingIdError as e:
122
+ logger.exception('任务启动冲突: %s', e)
123
+ messages.error(request, job_name + ' 任务启动发生冲突!')
124
+ job_num -= 1
125
+ except Exception as e:
126
+ logger.exception('任务启动异常: %s', e)
127
+ messages.error(request, job_name + ' 任务启动异常!<br/>请检查调度类型或执行频率')
128
+ job_num -= 1
129
+ if job_num > 0 and len(id_list) > 1:
130
+ messages.success(request,
131
+ ('其余' if job_num != len(id_list) else '所选') + ' %s 个任务启动成功' % str(job_num))
132
+ elif job_num == len(id_list) == 1:
133
+ messages.success(request, '%s 任务启动成功' % job_name)
134
+ return messages
135
+
136
+ start_job.short_description = '启动任务'
137
+ start_job.icon = 'el-icon-video-play'
138
+ start_job.type = 'success'
139
+
140
+ def stop_job(self, request, queryset):
141
+ global job_name
142
+ name_list = queryset.values('job_name')
143
+ trigger_list = queryset.values('trigger')
144
+ id_list = queryset.values('id')
145
+ job_num = len(id_list)
146
+ current_time = timezone.now()
147
+ for (trigger, id_, name) in zip(trigger_list, id_list, name_list):
148
+ try:
149
+ job_name = name.get('job_name')
150
+ job_id = id_.get('id')
151
+ trigger_name = JobList.objects.get(id=job_id).trigger.trigger_func
152
+ queryset.filter(id=job_id).update(job_state=0, update_time=current_time)
153
+ # 广播给所有 worker,立即从各自的调度器移除
154
+ publish_cmd('stop', trigger_name + '-' + str(job_id))
155
+ except Exception as e:
156
+ logger.exception('任务停止异常: %s', e)
157
+ job_num -= 1
158
+ messages.error(request, job_name + ' 任务停止异常!')
159
+ if job_num > 0 and len(id_list) > 1:
160
+ messages.success(request,
161
+ ('其余' if job_num != len(id_list) else '所选') + ' %s 个任务已停止' % str(job_num))
162
+ elif job_num == len(id_list) == 1:
163
+ messages.success(request, "%s 任务已停止" % job_name)
164
+ return messages
165
+
166
+ stop_job.short_description = '停止任务'
167
+ stop_job.icon = 'el-icon-video-pause'
168
+ stop_job.type = 'danger'
169
+
170
+ def action_job(self, request, queryset):
171
+ global job_name
172
+ job_num = len(queryset.values('id'))
173
+ if job_num > 1:
174
+ messages.error(request, "最多只能选择一个任务立即执行")
175
+ try:
176
+ id_ = queryset.values('id')[0]
177
+ name = queryset.values('job_name')[0]
178
+ job_name = name.get('job_name')
179
+ job_id = id_.get('id')
180
+ trigger_name = JobList.objects.get(id=job_id).trigger.trigger_func
181
+ if hasattr(JobAction, 'run_job'):
182
+ func = getattr(JobAction, 'run_job')
183
+ func(trigger_name, str(job_id))
184
+ else:
185
+ messages.error(request, '【启动错误】 ' + job_name + ' 任务不存在!')
186
+ messages.success(request, '%s 任务启动成功' % job_name)
187
+ except ConflictingIdError as e:
188
+ logger.exception('任务启动冲突: %s', e)
189
+ messages.error(request, job_name + ' 任务启动发生冲突!')
190
+ except Exception as e:
191
+ logger.exception('任务启动异常: %s', e)
192
+ messages.error(request, job_name + ' 任务启动异常!<br/>请检查调度类型或执行频率')
193
+ return messages
194
+
195
+ action_job.short_description = '立即执行'
196
+ action_job.icon = 'el-icon-video-play'
197
+ action_job.type = 'warning'
198
+ action_job.confirm = "确认立即执行?"
autojob/apps.py ADDED
@@ -0,0 +1,6 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class AutoJob(AppConfig):
5
+ default_auto_field = 'django.db.models.BigAutoField'
6
+ name = 'autojob'
@@ -0,0 +1,138 @@
1
+ # coding=utf-8
2
+ """定时任务指令广播:把 Admin 的操作实时同步到每个 worker 进程。
3
+
4
+ 为什么是线程而不是进程:
5
+ APScheduler 实例保存在各个 worker 进程自己的内存里,
6
+ 子进程无法操作父进程的调度器,所以只能在每个进程内各起一个线程。
7
+
8
+ 为什么用 Pub/Sub 而不是轮询 Redis key:
9
+ 发布方 publish 一次,所有订阅者立刻收到,延迟从"最长 60 秒"降到毫秒级,
10
+ 也不再需要每个 worker 每分钟全量扫描一遍 key。
11
+ """
12
+ import json
13
+ import logging
14
+ import os
15
+ import threading
16
+ import time
17
+ import uuid
18
+
19
+ import redis
20
+ from django.conf import settings
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+ # 进程内守卫:同一个进程只允许起一个监听线程
25
+ _started_pid = None
26
+ _guard = threading.Lock()
27
+ _client = None
28
+
29
+
30
+ def _get_client():
31
+ global _client
32
+ if _client is None:
33
+ _client = redis.Redis.from_url(settings.JOB_CMD_REDIS_URL)
34
+ return _client
35
+
36
+
37
+ def _claim_cmd_log(cmd_id):
38
+ """同一指令只允许一个实际执行成功的 worker 记录日志。"""
39
+ if not cmd_id:
40
+ return True
41
+ key = '%s:executed:%s' % (settings.JOB_CMD_CHANNEL, cmd_id)
42
+ return bool(_get_client().set(key, os.getpid(), nx=True, ex=10))
43
+
44
+
45
+ def publish_cmd(op, job_id, value=None):
46
+ """发布一条任务指令,所有 worker 都会收到。
47
+
48
+ op: 'stop' | 'modify'
49
+ job_id: 调度器里的任务 id,格式为 ``{trigger_func}-{JobList.id}``
50
+ value: modify 时为新值 (action_type, job_rate)
51
+ """
52
+ payload = {'op': op, 'job_id': job_id, 'cmd_id': uuid.uuid4().hex}
53
+ if value is not None:
54
+ payload['value'] = value
55
+ # 必须先写发布日志再广播,否则其他 worker 可能先记录接收日志。
56
+ logger.info('发布 %s 指令 %s', op, payload)
57
+ try:
58
+ receivers = _get_client().publish(settings.JOB_CMD_CHANNEL, json.dumps(payload))
59
+ except redis.RedisError:
60
+ # 发布失败不影响 Admin 操作本身:DB 状态已是准绳,
61
+ # 停止指令会在任务下次触发时由 job_before 里的 job_state 检查兜底
62
+ logger.exception('指令发布失败,已降级为数据库状态兜底: %s', payload)
63
+ return 0
64
+ logger.debug('指令发布完成,在线订阅者 %s 个', receivers)
65
+ return receivers
66
+
67
+
68
+ def start_listener():
69
+ """在当前进程内启动指令监听线程(幂等)。"""
70
+ global _started_pid
71
+ pid = os.getpid()
72
+ with _guard:
73
+ if _started_pid == pid:
74
+ return False
75
+ _started_pid = pid
76
+ thread = threading.Thread(
77
+ target=_listen_forever, name='autojob-cmd-%s' % pid, daemon=True
78
+ )
79
+ thread.start()
80
+ logger.debug('任务指令监听线程已启动, pid=%s', pid)
81
+ return True
82
+
83
+
84
+ def _listen_forever():
85
+ """订阅循环,断线后自动重连。"""
86
+ pubsub = None
87
+ while True:
88
+ try:
89
+ if pubsub is None:
90
+ client = redis.Redis.from_url(
91
+ settings.JOB_CMD_REDIS_URL, health_check_interval=30
92
+ )
93
+ pubsub = client.pubsub(ignore_subscribe_messages=True)
94
+ pubsub.subscribe(settings.JOB_CMD_CHANNEL)
95
+ logger.debug(
96
+ '已订阅 %s, pid=%s', settings.JOB_CMD_CHANNEL, os.getpid()
97
+ )
98
+ message = pubsub.get_message(timeout=5)
99
+ if message is None:
100
+ continue
101
+ _handle(json.loads(message['data']))
102
+ except Exception:
103
+ logger.exception('任务指令监听中断,3 秒后重连')
104
+ if pubsub is not None:
105
+ try:
106
+ pubsub.close()
107
+ except Exception:
108
+ pass
109
+ pubsub = None
110
+ time.sleep(3)
111
+
112
+
113
+ def _handle(payload):
114
+ from autojob.job_new import JobAction
115
+ from apscheduler.jobstores.base import JobLookupError
116
+
117
+ op = payload.get('op')
118
+ job_id = payload.get('job_id')
119
+ if not job_id:
120
+ return
121
+ try:
122
+ # 所有 worker 都会收到广播,同一指令只由第一个执行成功者记录日志。
123
+ if op == 'stop':
124
+ if JobAction.stop_job(job_id) and _claim_cmd_log(payload.get('cmd_id')):
125
+ logger.info('%s 指令执行完成: %s, worker_pid=%s', op, job_id, os.getpid())
126
+ elif op == 'modify':
127
+ if JobAction.modify_job(job_id, payload.get('value')) and _claim_cmd_log(payload.get('cmd_id')):
128
+ logger.info(
129
+ '%s 指令执行完成: %s -> %s, worker_pid=%s',
130
+ op, job_id, payload.get('value'), os.getpid()
131
+ )
132
+ else:
133
+ logger.warning('收到未知指令: %s', payload)
134
+ except JobLookupError:
135
+ # 广播期间任务被移除属于正常情况,其他 worker 不再重复记录警告。
136
+ logger.debug('本进程没有任务,忽略指令: %s, pid=%s', payload, os.getpid())
137
+ except Exception:
138
+ logger.exception('处理指令失败: %s', payload)
autojob/job_new.py ADDED
@@ -0,0 +1,204 @@
1
+ # coding=utf-8
2
+ import logging
3
+ import re
4
+ from datetime import datetime
5
+
6
+ from apscheduler.schedulers.background import BackgroundScheduler
7
+ from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR, EVENT_JOB_MISSED
8
+ from django.utils.module_loading import import_string
9
+
10
+ from autojob.models import JobList
11
+
12
+ logging.getLogger('apscheduler.executors.default').setLevel(logging.WARNING)
13
+ logging.getLogger('apscheduler.scheduler').setLevel(logging.WARNING)
14
+ logger = logging.getLogger(__name__)
15
+
16
+
17
+ def start_scheduler():
18
+ """启动调度器;同一进程内只启动一次,重复调用返回 False。"""
19
+ global scheduler
20
+ if 'scheduler' in globals() and scheduler.running:
21
+ return False
22
+ scheduler = BackgroundScheduler(
23
+ job_defaults={
24
+ 'misfire_grace_time': 60,
25
+ 'coalesce': True,
26
+ },
27
+ executors={
28
+ 'default': {'type': 'threadpool', 'max_workers': 30}
29
+ }
30
+ )
31
+ scheduler.add_listener(JobAction.my_listener, EVENT_JOB_ERROR | EVENT_JOB_MISSED | EVENT_JOB_EXECUTED)
32
+ scheduler.start()
33
+ return True
34
+
35
+
36
+ def _parse_interval(rate):
37
+ """解析 interval 执行频率:秒 分 时(空格分隔,缺省为 0,至少一项大于 0)。"""
38
+ parts = rate.split()
39
+ if not 1 <= len(parts) <= 3:
40
+ raise ValueError('interval 执行频率格式为「秒 分 时」,最多 3 项,例:30 或 0 5')
41
+ try:
42
+ values = [int(part) for part in parts]
43
+ except ValueError:
44
+ raise ValueError('interval 执行频率必须是整数,例:30 或 0 5') from None
45
+ values += [0] * (3 - len(values))
46
+ if any(value < 0 for value in values):
47
+ raise ValueError('interval 执行频率不能为负数')
48
+ if not any(values):
49
+ raise ValueError('interval 执行频率不能全为 0')
50
+ return {'seconds': values[0], 'minutes': values[1], 'hours': values[2]}
51
+
52
+
53
+ _CRON_RANGES = (
54
+ ('秒', 0, 59), ('分', 0, 59), ('时', 0, 23),
55
+ ('日', 1, 31), ('月', 1, 12), ('星期', 0, 6), ('年', 1970, 9999),
56
+ )
57
+
58
+ _DATE_RE = re.compile(
59
+ r'^(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})'
60
+ r'(?:[ T](?P<hour>\d{1,2}):(?P<minute>\d{1,2}):(?P<second>\d{1,2})'
61
+ r'(?:\.(?P<microsecond>\d{1,6}))?(?P<tz>Z|[+-]\d\d:\d\d)?)?$'
62
+ )
63
+
64
+
65
+ def _check_cron_field(name, value, low, high):
66
+ """校验 cron 单个字段:支持 *、数字、区间、步长及逗号列表。"""
67
+ allow_name = name in ('月', '星期')
68
+ for item in value.split(','):
69
+ expr, _, step = item.partition('/')
70
+ if not expr:
71
+ raise ValueError('cron %s 存在空项:%s' % (name, value))
72
+ if step and (not step.isdigit() or int(step) <= 0):
73
+ raise ValueError('cron %s 步长必须是正整数:%s' % (name, item))
74
+ if expr == '*':
75
+ continue
76
+ if any(char.isalpha() for char in expr):
77
+ if allow_name:
78
+ # jan、mon 之类的英文缩写交给 APScheduler 校验
79
+ continue
80
+ raise ValueError('cron %s 仅支持数字、*、区间和步长,当前为:%s' % (name, item))
81
+ try:
82
+ start, _, end = expr.partition('-')
83
+ values = [int(start)] + ([int(end)] if end else [])
84
+ except ValueError:
85
+ raise ValueError('cron %s 仅支持数字、*、区间和步长,当前为:%s' % (name, item)) from None
86
+ if any(not low <= number <= high for number in values):
87
+ raise ValueError('cron %s 取值范围为 %s-%s,当前为:%s' % (name, low, high, item))
88
+ if len(values) == 2 and values[0] > values[1]:
89
+ raise ValueError('cron %s 区间起始值不能大于结束值:%s' % (name, item))
90
+
91
+
92
+ def _parse_cron(rate):
93
+ """解析 cron 执行频率:秒 分 时 日 月 星期 年,共 7 项。"""
94
+ parts = rate.split()
95
+ if len(parts) != 7:
96
+ raise ValueError('cron 执行频率格式为「秒 分 时 日 月 星期 年」,共 7 项,例:0 0 2 * * * *')
97
+ for part, (name, low, high) in zip(parts, _CRON_RANGES):
98
+ _check_cron_field(name, part, low, high)
99
+ return {'second': parts[0], 'minute': parts[1], 'hour': parts[2], 'day': parts[3],
100
+ 'month': parts[4], 'day_of_week': parts[5], 'year': parts[6]}
101
+
102
+
103
+ def _parse_date(value):
104
+ """校验 date 执行频率:2019-8-30 01:00:00,格式与 APScheduler 保持一致。"""
105
+ text = value.strip() if isinstance(value, str) else ''
106
+ if not text:
107
+ raise ValueError('date 执行频率不能为空,例:2019-8-30 01:00:00')
108
+ match = _DATE_RE.match(text)
109
+ if not match:
110
+ raise ValueError('date 执行频率格式应为 YYYY-MM-DD HH:MM:SS,例:2019-8-30 01:00:00')
111
+ try:
112
+ datetime(**{key: int(number) for key, number in match.groupdict().items()
113
+ if key != 'tz' and number})
114
+ except ValueError:
115
+ raise ValueError('date 执行频率不是有效的日期时间:%s' % text) from None
116
+ return text
117
+
118
+
119
+ _JOB_RATE_PARSERS = {
120
+ 'date': _parse_date, 'cron': _parse_cron, 'interval': _parse_interval,
121
+ }
122
+
123
+
124
+ def parse_job_rate(action_type, rate):
125
+ """按调度类型校验执行频率,非法时抛出 ValueError。"""
126
+ parser = _JOB_RATE_PARSERS.get(action_type)
127
+ if parser is not None:
128
+ parser(rate)
129
+
130
+
131
+ def load_job_func(func_path):
132
+ """把「from 模块 import 函数」解析成可调用对象,非法时抛出 ValueError。"""
133
+ parts = func_path.split()
134
+ if len(parts) != 4 or parts[0] != 'from' or parts[2] != 'import':
135
+ raise ValueError('触发器路径格式应为「from 模块 import 函数」,例:from autojob.test_job import test')
136
+ try:
137
+ func = import_string('%s.%s' % (parts[1], parts[3]))
138
+ except ImportError as exc:
139
+ raise ValueError('触发器路径无法导入:%s(%s)' % (func_path, exc)) from None
140
+ if not callable(func):
141
+ raise ValueError('触发器路径指向的对象不可调用:%s' % func_path)
142
+ return func
143
+
144
+
145
+ class JobAction:
146
+ @staticmethod
147
+ def start_date_job(trigger, job_rate, id):
148
+ func = load_job_func(JobList.objects.get(id=id).trigger.func_path)
149
+ trigger_id = trigger + '-' + id
150
+ scheduler.add_job(func, 'date', run_date=_parse_date(job_rate), id=trigger_id,
151
+ args=[trigger_id, id, 'date'], replace_existing=True)
152
+
153
+ @staticmethod
154
+ def start_cron_job(trigger, job_rate, id):
155
+ func = load_job_func(JobList.objects.get(id=id).trigger.func_path)
156
+ trigger_id = trigger + '-' + id
157
+ # 秒 分 时 日 月 星期 年
158
+ scheduler.add_job(func, 'cron', id=trigger_id, args=[trigger_id, id, 'cron'],
159
+ replace_existing=True, **_parse_cron(job_rate))
160
+
161
+ @staticmethod
162
+ def start_interval_job(trigger, job_rate, id):
163
+ func = load_job_func(JobList.objects.get(id=id).trigger.func_path)
164
+ trigger_id = trigger + '-' + id
165
+ scheduler.add_job(func, 'interval', id=trigger_id, args=[trigger_id, id, 'interval'],
166
+ replace_existing=True, **_parse_interval(job_rate))
167
+
168
+ @staticmethod
169
+ def run_job(trigger, id):
170
+ func = load_job_func(JobList.objects.get(id=id).trigger.func_path)
171
+ trigger_id = trigger + '-' + id
172
+ scheduler.add_job(func, 'date', run_date=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
173
+ id=trigger_id, args=[trigger_id, id, 'now'])
174
+
175
+ # 停止任务
176
+ @staticmethod
177
+ def stop_job(trigger_id):
178
+ if not scheduler.get_job(trigger_id):
179
+ return False
180
+ scheduler.remove_job(trigger_id)
181
+ return True
182
+
183
+ # 修改任务
184
+ @staticmethod
185
+ def modify_job(trigger_id, job_value):
186
+ if not scheduler.get_job(trigger_id):
187
+ return False
188
+ if job_value[0] == 'cron':
189
+ scheduler.reschedule_job(trigger_id, trigger='cron', **_parse_cron(job_value[1]))
190
+ return True
191
+ if job_value[0] == 'date':
192
+ scheduler.reschedule_job(trigger_id, trigger='date', run_date=_parse_date(job_value[1]))
193
+ return True
194
+ if job_value[0] == 'interval':
195
+ scheduler.reschedule_job(trigger_id, trigger='interval', **_parse_interval(job_value[1]))
196
+ return True
197
+ return False
198
+
199
+ @staticmethod
200
+ def my_listener(event):
201
+ if event.exception:
202
+ job = scheduler.get_job(event.job_id)
203
+ logger.error("jobname=%s|jobtrigger=%s|errcode=%s|exception=[%s]|traceback=[%s]|scheduled_time=%s",
204
+ job.name, job.trigger, event.code, event.exception, event.traceback, event.scheduled_run_time)
autojob/job_tool.py ADDED
@@ -0,0 +1,64 @@
1
+ import logging
2
+ from functools import wraps
3
+
4
+ from django.core.cache import cache
5
+ from django.utils import timezone
6
+
7
+ from autojob.models import JobList
8
+
9
+ logger = logging.getLogger(__name__)
10
+
11
+
12
+ def job_before(func):
13
+ @wraps(func)
14
+ def wrapper(*args, **kwargs):
15
+ from autojob.job_new import JobAction
16
+ if args[2] == 'now':
17
+ return func(*args, **kwargs)
18
+ job = JobList.objects.filter(id=int(args[1])).values('job_state', 'action_type')[0]
19
+ if job['job_state'] != 1:
20
+ # 已在 Admin 中被停止,把本进程调度器里的任务移除
21
+ JobAction.stop_job(args[0])
22
+ return
23
+ if not get_lock(args[0]):
24
+ # 其他 worker 正在执行,本进程不再重复执行
25
+ JobAction.stop_job(args[0])
26
+ return
27
+ # 一次性任务执行完自动置为停止,避免重复触发
28
+ if job['action_type'] == 'date':
29
+ JobList.objects.filter(id=int(args[1])).update(job_state=0, update_time=timezone.now())
30
+ func(*args, **kwargs)
31
+
32
+ wrapper._is_decorated = True
33
+ return wrapper
34
+
35
+
36
+ def get_lock(lock_name):
37
+ lock = cache.lock('lock.' + lock_name, timeout=5)
38
+ return lock.acquire(blocking=False)
39
+
40
+
41
+ def job_control():
42
+ try:
43
+ from autojob.job_new import JobAction
44
+ from autojob import job_new
45
+
46
+ # 同一进程内重复调用时,调度器已启动且任务已恢复,直接跳过
47
+ if not job_new.start_scheduler():
48
+ return
49
+
50
+ job_list_ = JobList.objects.filter(job_state=1)
51
+ # 多 worker 同轮启动只记录一次,短期 TTL 允许后续重启再次记录。
52
+ if cache.add('autojob:startup-log', 1, timeout=20):
53
+ logger.info('程序启动,恢复未完成的定时任务 : %s', len(job_list_))
54
+ # 每个 worker 进程内各起一个指令监听线程,实时接收 Admin 的停止/修改指令
55
+ from autojob.cmd_listener import start_listener
56
+ start_listener()
57
+ for job_ in job_list_:
58
+ if hasattr(JobAction, 'start_%s_job' % job_.action_type):
59
+ func = getattr(JobAction, 'start_%s_job' % job_.action_type)
60
+ func(job_.trigger.trigger_func, job_.job_rate, str(job_.id))
61
+ else:
62
+ logger.error('【启动错误】 ' + job_.trigger.trigger_func + '任务不存在!')
63
+ except Exception as rel:
64
+ logger.exception('scheduler start error: %s', rel)
File without changes
File without changes