django-autojob 1.0.0__tar.gz

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.
@@ -0,0 +1,27 @@
1
+ Copyright (c) The Wharton School and individual contributors.
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without modification,
5
+ are permitted provided that the following conditions are met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright notice,
8
+ this list of conditions and the following disclaimer.
9
+
10
+ 2. Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+
14
+ 3. Neither the name of DRF Renderer XLSX nor the names of its contributors
15
+ may be used to endorse or promote products derived from this software
16
+ without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
22
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
25
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,2 @@
1
+ include LICENSE
2
+ include README.md
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.1
2
+ Name: django-autojob
3
+ Version: 1.0.0
4
+ Summary: Django customizes management pages based on APScheduler
5
+ Home-page: https://github.com/lmycc/autojob
6
+ Author: zkrliumy
7
+ Author-email: zkrliumy@163.com
8
+ License: UNKNOWN
9
+ Description: # README.md
10
+ - [English](https://github.com/lmycc/autojob/blob/main/README.md)
11
+ - [简体中文](https://github.com/lmycc/autojob/blob/main/README.zh_CN.md)
12
+
13
+ # AutoJob
14
+
15
+ #### AutoJob 是整合了APScheduler和Django的一个定时任务app,只需安装依赖,通过一定配置即可完成定时任务的开发,可通过页面管理定时任务的编辑和状态变更
16
+ #### 该app解决了在 Django + uwsgi 部署应用时,启动多个进程会导致定时任务启动冲突的情况
17
+ #### 暂只支持`corn`和`date`两种类型,本地需安装redis
18
+ #### 该定时任务还适配了simple-ui前端框架
19
+
20
+ ## 安装方式
21
+ ```
22
+ pip install autojob
23
+ ```
24
+ ## 使用方式
25
+
26
+ ### 1. 添加 "autojob" 到 `settings.py`的 INSTALLED_APPS 中:
27
+ ```
28
+ INSTALLED_APPS = [
29
+ ...
30
+ 'autojob.apps.AutoJob',
31
+ ]
32
+ ```
33
+
34
+ ### 2. 执行 `python manage.py migrate autojob` 迁移数据表,下面是添加触发器的方式
35
+ #### 两种录入自定义定时任务的方式
36
+ - **终端命令方式**
37
+ ```
38
+ ## django项目中编写了自定义的定时任务后,可以在终端执行以下命令:
39
+ python manage.py scan_jobs
40
+
41
+ ##返回以下信息,即表示成功添加了定时任务触发器到数据表中(重复执行不会导致重复添加):
42
+ ###检测到新增定时任务:myapp.abc.job_test
43
+ ```
44
+ - **代码调用方式**
45
+ ```
46
+ ## 这种方式是在`wsgi.py`文件中增加对command的引用来录入自定义定时任务触发器
47
+ from app.management.commands.scan_jobs import Command
48
+ scan_jobs = Command()
49
+ scan_jobs.handle()
50
+
51
+ ##返回以下信息,即表示成功添加了定时任务触发器到数据表中(重复执行不会导致重复添加):
52
+ ###检测到新增定时任务:myapp.abc.job_test
53
+ ```
54
+
55
+ ### 3. django应用启动时调用定时任务,在 `wsgi.py`中添加:
56
+ ```
57
+ from autojob import job_tool
58
+ job_tool.job_control()
59
+ ```
60
+
61
+ ### 4. 在 `settings.py`添加redis配置
62
+ ```
63
+ CACHES = {
64
+ "default": {
65
+ "BACKEND": "django_redis.cache.RedisCache",
66
+ "LOCATION": "redis://127.0.0.1:6379/0",
67
+ "OPTIONS": {
68
+ "PICK_VERSION": -1,
69
+ "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor",
70
+ "CLIENT_CLASS": "django_redis.client.DefaultClient",
71
+ "PASSWORD": ""
72
+ }
73
+ }
74
+ }
75
+ ```
76
+
77
+ ### 5. 一个测试任务的demo: `job_test.py`
78
+
79
+ ```
80
+ # coding=utf-8
81
+ import datetime
82
+ import logging
83
+
84
+ from app.job_tool import job_before
85
+
86
+ logger = logging.getLogger(__name__)
87
+
88
+
89
+ @job_before
90
+ def job_test(*args):
91
+ # 当应用程序启动时,录入任务触发器时会读取下面这行文档当做触发器的描述,如果没有则默认描述是函数的路径
92
+ """一个测试的定时任务"""
93
+ now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
94
+ logger.info(now + '__This is a timed task for testing:' + args[0])
95
+ ```
96
+
97
+
98
+ Keywords: autojob
99
+ Platform: UNKNOWN
100
+ Classifier: Development Status :: 5 - Production/Stable
101
+ Classifier: Environment :: Web Environment
102
+ Classifier: Intended Audience :: Developers
103
+ Classifier: License :: OSI Approved :: BSD License
104
+ Classifier: Operating System :: OS Independent
105
+ Classifier: Programming Language :: Python
106
+ Classifier: Programming Language :: Python :: 3
107
+ Classifier: Programming Language :: Python :: 3.6
108
+ Classifier: Programming Language :: Python :: 3.7
109
+ Classifier: Programming Language :: Python :: 3.8
110
+ Classifier: Programming Language :: Python :: 3.9
111
+ Classifier: Programming Language :: Python :: 3.10
112
+ Classifier: Programming Language :: Python :: 3 :: Only
113
+ Classifier: Framework :: Django
114
+ Classifier: Framework :: Django :: 2
115
+ Classifier: Framework :: Django :: 3
116
+ Classifier: Framework :: Django :: 4
117
+ Description-Content-Type: text/markdown
@@ -0,0 +1,88 @@
1
+ # README.md
2
+ - [English](https://github.com/lmycc/autojob/blob/main/README.md)
3
+ - [简体中文](https://github.com/lmycc/autojob/blob/main/README.zh_CN.md)
4
+
5
+ # AutoJob
6
+
7
+ #### AutoJob 是整合了APScheduler和Django的一个定时任务app,只需安装依赖,通过一定配置即可完成定时任务的开发,可通过页面管理定时任务的编辑和状态变更
8
+ #### 该app解决了在 Django + uwsgi 部署应用时,启动多个进程会导致定时任务启动冲突的情况
9
+ #### 暂只支持`corn`和`date`两种类型,本地需安装redis
10
+ #### 该定时任务还适配了simple-ui前端框架
11
+
12
+ ## 安装方式
13
+ ```
14
+ pip install autojob
15
+ ```
16
+ ## 使用方式
17
+
18
+ ### 1. 添加 "autojob" 到 `settings.py`的 INSTALLED_APPS 中:
19
+ ```
20
+ INSTALLED_APPS = [
21
+ ...
22
+ 'autojob.apps.AutoJob',
23
+ ]
24
+ ```
25
+
26
+ ### 2. 执行 `python manage.py migrate autojob` 迁移数据表,下面是添加触发器的方式
27
+ #### 两种录入自定义定时任务的方式
28
+ - **终端命令方式**
29
+ ```
30
+ ## django项目中编写了自定义的定时任务后,可以在终端执行以下命令:
31
+ python manage.py scan_jobs
32
+
33
+ ##返回以下信息,即表示成功添加了定时任务触发器到数据表中(重复执行不会导致重复添加):
34
+ ###检测到新增定时任务:myapp.abc.job_test
35
+ ```
36
+ - **代码调用方式**
37
+ ```
38
+ ## 这种方式是在`wsgi.py`文件中增加对command的引用来录入自定义定时任务触发器
39
+ from app.management.commands.scan_jobs import Command
40
+ scan_jobs = Command()
41
+ scan_jobs.handle()
42
+
43
+ ##返回以下信息,即表示成功添加了定时任务触发器到数据表中(重复执行不会导致重复添加):
44
+ ###检测到新增定时任务:myapp.abc.job_test
45
+ ```
46
+
47
+ ### 3. django应用启动时调用定时任务,在 `wsgi.py`中添加:
48
+ ```
49
+ from autojob import job_tool
50
+ job_tool.job_control()
51
+ ```
52
+
53
+ ### 4. 在 `settings.py`添加redis配置
54
+ ```
55
+ CACHES = {
56
+ "default": {
57
+ "BACKEND": "django_redis.cache.RedisCache",
58
+ "LOCATION": "redis://127.0.0.1:6379/0",
59
+ "OPTIONS": {
60
+ "PICK_VERSION": -1,
61
+ "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor",
62
+ "CLIENT_CLASS": "django_redis.client.DefaultClient",
63
+ "PASSWORD": ""
64
+ }
65
+ }
66
+ }
67
+ ```
68
+
69
+ ### 5. 一个测试任务的demo: `job_test.py`
70
+
71
+ ```
72
+ # coding=utf-8
73
+ import datetime
74
+ import logging
75
+
76
+ from app.job_tool import job_before
77
+
78
+ logger = logging.getLogger(__name__)
79
+
80
+
81
+ @job_before
82
+ def job_test(*args):
83
+ # 当应用程序启动时,录入任务触发器时会读取下面这行文档当做触发器的描述,如果没有则默认描述是函数的路径
84
+ """一个测试的定时任务"""
85
+ now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
86
+ logger.info(now + '__This is a timed task for testing:' + args[0])
87
+ ```
88
+
File without changes
@@ -0,0 +1,137 @@
1
+ from apscheduler.jobstores.base import ConflictingIdError, JobLookupError
2
+ from django.contrib import admin
3
+ from django.core.cache import cache
4
+ from django.utils import timezone
5
+
6
+ from autojob.job_new import JobAction
7
+
8
+ from .models import JobList, JobTrigger
9
+ import logging
10
+ from django.contrib import messages
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ # Register your models here.
16
+ @admin.register(JobTrigger)
17
+ class JobListTriggerAdmin(admin.ModelAdmin):
18
+ list_display = ('id', 'trigger_name', 'trigger_func', 'func_path', 'description')
19
+ list_display_links = ('id', 'trigger_name')
20
+ list_per_page = 20
21
+ list_max_show_all = 7
22
+ ordering = ('id',)
23
+
24
+
25
+ # Register your models here.
26
+ @admin.register(JobList)
27
+ class JobListAdmin(admin.ModelAdmin):
28
+ list_display = ('id', 'job_name', 'job_state', 'action_type', 'job_rate', 'update_time')
29
+ list_display_links = ('id', 'job_name')
30
+ list_filter = ('job_state',)
31
+ list_editable = ('action_type', 'job_rate',)
32
+ list_per_page = 20
33
+ list_max_show_all = 7
34
+ ordering = ('-job_state', 'id',)
35
+ actions = ['start_job', 'stop_job']
36
+
37
+ def get_readonly_fields(self, request, obj=None):
38
+ if obj:
39
+ readonly_fields = ('trigger_id', 'job_state', 'update_time',)
40
+ else:
41
+ readonly_fields = ('job_state',)
42
+ return readonly_fields
43
+
44
+ def save_model(self, request, obj, form, change):
45
+ if obj.job_state == 1:
46
+ cache.set('modify_' + obj.trigger.trigger_func + '-' + str(obj.id), (obj.action_type, obj.job_rate),
47
+ timeout=60)
48
+ obj.save()
49
+
50
+ def start_job(self, request, queryset):
51
+ global job_name
52
+ trigger_list = queryset.values('trigger_id')
53
+ rate_list = queryset.values('job_rate')
54
+ id_list = queryset.values('id')
55
+ job_num = len(id_list)
56
+ name_list = queryset.values('job_name')
57
+ action_type = queryset.values('action_type')
58
+ update_time = queryset.values('update_time')
59
+ current_time = timezone.now()
60
+ for (trigger, rate, id_, name, type_, time_) in zip(trigger_list, rate_list, id_list, name_list, action_type,
61
+ update_time):
62
+ try:
63
+ job_name = name.get('job_name')
64
+ job_rate = rate.get('job_rate')
65
+ job_id = id_.get('id')
66
+ trigger_name = JobList.objects.get(id=job_id).trigger.trigger_func
67
+ job_type = type_.get('action_type')
68
+ last_time = time_.get('update_time')
69
+ interval_time = current_time - last_time
70
+ seconds = interval_time.days * 24 * 3600 + interval_time.seconds
71
+ if seconds < 60:
72
+ messages.warning(request, 'Please start %s again with %ss' % (job_name, str(60 - seconds)))
73
+ job_num -= 1
74
+ continue
75
+ if hasattr(JobAction(), 'start_%s_job' % job_type):
76
+ func = getattr(JobAction(), 'start_%s_job' % job_type)
77
+ func(trigger_name, job_rate, str(job_id))
78
+ queryset.filter(id=job_id).update(job_state=1, update_time=current_time)
79
+ else:
80
+ messages.error(request, '【start failed】: ' + job_name + ' job does not exists!!')
81
+ job_num -= 1
82
+ except ConflictingIdError as e:
83
+ logger.error(e)
84
+ messages.error(request, job_name + ' job startup conflict occurred!!')
85
+ job_num -= 1
86
+ except Exception as e:
87
+ logger.error(e)
88
+ messages.error(request, job_name + ' job start error!<br/>Check the scheduling type or frequency')
89
+ job_num -= 1
90
+ JobAction().get_jobs()
91
+ if job_num > 0 and len(id_list) > 1:
92
+ messages.success(request,
93
+ ('the rest' if job_num != len(
94
+ id_list) else 'selected') + ' %s jobs were successfully started' % str(job_num))
95
+ elif job_num == len(id_list) == 1:
96
+ messages.success(request, '%s job started successfully' % job_name)
97
+ return messages
98
+
99
+ start_job.short_description = '启动任务'
100
+ start_job.icon = 'el-icon-video-play'
101
+ start_job.type = 'success'
102
+
103
+ def stop_job(self, request, queryset):
104
+ global job_name
105
+ name_list = queryset.values('job_name')
106
+ trigger_list = queryset.values('trigger')
107
+ id_list = queryset.values('id')
108
+ job_num = len(id_list)
109
+ current_time = timezone.now()
110
+ for (trigger, id_, name) in zip(trigger_list, id_list, name_list):
111
+ try:
112
+ job_name = name.get('job_name')
113
+ job_id = id_.get('id')
114
+ trigger_name = JobList.objects.get(id=job_id).trigger.trigger_func
115
+ JobAction.stop_job(trigger_name + '-' + str(job_id))
116
+ queryset.filter(id=job_id).update(job_state=0, update_time=current_time)
117
+ cache.set('stop_' + str(job_id), trigger_name + '-' + str(job_id), timeout=60)
118
+ except JobLookupError as e:
119
+ logger.error(e)
120
+ job_num -= 1
121
+ messages.error(request, job_name + " job does not exists!!!")
122
+ except Exception as e:
123
+ logger.error(e)
124
+ job_num -= 1
125
+ messages.error(request, job_name + ' job stop error!')
126
+ JobAction().get_jobs()
127
+ if job_num > 0 and len(id_list) > 1:
128
+ messages.success(request,
129
+ ('the rest' if job_num != len(
130
+ id_list) else 'selected') + ' %s jobs were successfully stopped' % str(job_num))
131
+ elif job_num == len(id_list) == 1:
132
+ messages.success(request, "%s has been stopped" % job_name)
133
+ return messages
134
+
135
+ stop_job.short_description = '停止任务'
136
+ stop_job.icon = 'el-icon-video-pause'
137
+ stop_job.type = 'danger'
@@ -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,89 @@
1
+ # coding=utf-8
2
+ import logging
3
+ import os
4
+
5
+ from apscheduler.schedulers.background import BackgroundScheduler
6
+ from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR, EVENT_JOB_MISSED
7
+
8
+ from autojob.models import JobList
9
+
10
+ logging.getLogger('apscheduler.executors.default').setLevel(logging.WARNING)
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ def start_scheduler():
15
+ global scheduler
16
+ scheduler = BackgroundScheduler(timezone='Asia/Shanghai')
17
+ scheduler.start()
18
+ from .job_tool import monitor_job_status
19
+ scheduler.add_job(monitor_job_status, 'cron', second=0, minute='*/1', hour='*', day='*', month='*', day_of_week='*',
20
+ year='*', id='monitor_job_status-0', replace_existing=True)
21
+
22
+
23
+ class JobAction:
24
+ def __init__(self):
25
+ self.scheduler = scheduler
26
+ self.scheduler.add_listener(self.my_listener, EVENT_JOB_ERROR | EVENT_JOB_MISSED | EVENT_JOB_EXECUTED)
27
+
28
+ # start job for date
29
+ @staticmethod
30
+ def start_date_job(trigger, job_rate, id):
31
+ exec(JobList.objects.get(id=id).trigger.func_path)
32
+ trigger_id = trigger + '-' + id
33
+ scheduler.add_job(eval(trigger), 'date', run_date=job_rate, id=trigger_id, args=[trigger_id, id, 'date'],
34
+ replace_existing=True, coalesce=True)
35
+
36
+ # start job for cron
37
+ @staticmethod
38
+ def start_cron_job(trigger, job_rate, id):
39
+ exec(JobList.objects.get(id=id).trigger.func_path)
40
+ rate = job_rate.split()
41
+ trigger_id = trigger + '-' + id
42
+ # second minute hour day month week year (The parameters must be in this order)
43
+ scheduler.add_job(eval(trigger), 'cron', second=rate[0], minute=rate[1], hour=rate[2], day=rate[3],
44
+ month=rate[4], day_of_week=rate[5], year=rate[6], id=trigger_id,
45
+ args=[trigger_id, id, 'cron'], replace_existing=True, coalesce=True)
46
+
47
+ # stop job
48
+ @staticmethod
49
+ def stop_job(trigger_id):
50
+ if scheduler.get_job(trigger_id):
51
+ scheduler.remove_job(trigger_id)
52
+
53
+ # pause job
54
+ @staticmethod
55
+ def pause_job(trigger_id):
56
+ logger.info(trigger_id)
57
+ scheduler.pause_job(trigger_id)
58
+
59
+ # restart job
60
+ @staticmethod
61
+ def resume_job(trigger_id):
62
+ scheduler.resume_job(trigger_id)
63
+
64
+ # modify job
65
+ @staticmethod
66
+ def modify_job(trigger_id, job_value):
67
+ if scheduler.get_job(trigger_id):
68
+ logger.info('modify job:' + trigger_id + '\t' + str(job_value))
69
+ if job_value[0] == 'cron':
70
+ rate = job_value[1].split()
71
+ scheduler.reschedule_job(trigger_id, trigger='cron', second=rate[0], minute=rate[1], hour=rate[2],
72
+ day=rate[3], month=rate[4], day_of_week=rate[5], year=rate[6])
73
+ elif job_value[0] == 'date':
74
+ scheduler.reschedule_job(trigger_id, trigger='date', run_date=job_value[1])
75
+
76
+ @staticmethod
77
+ def get_jobs():
78
+ jobs = [item.id for item in scheduler.get_jobs()]
79
+ logger.info(str(os.getpid()) + ' - all jobs:' + str(jobs))
80
+
81
+ @staticmethod
82
+ def my_listener(event): # Add listener
83
+ job = scheduler.get_job(event.job_id)
84
+ if not event.exception:
85
+ pass
86
+ else:
87
+ logger.error("jobname=%s|jobtrigger=%s|errcode=%s|exception=[%s]|traceback=[%s]|scheduled_time=%s",
88
+ job.name, job.trigger, event.code, event.exception, event.traceback, event.scheduled_run_time)
89
+ # scheduler.shutdown(wait=False)
@@ -0,0 +1,15 @@
1
+ # coding=utf-8
2
+ import datetime
3
+ import logging
4
+
5
+ from autojob.job_tool import job_before
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+
10
+ @job_before
11
+ def job_test(*args):
12
+ # 应用启动时,job自动扫描会自动读取下面这行文档描述,当做job的描述,不写的话则默认为job的路径
13
+ """This is a timed task for testing"""
14
+ now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
15
+ logger.info(now + '__This is a timed task for testing:' + args[0])
@@ -0,0 +1,71 @@
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
+ job_state = JobList.objects.filter(id=int(args[1])).values('job_state')[0]['job_state']
17
+ if job_state == 1:
18
+ job_value = cache.get('modify_' + args[0])
19
+ if job_value:
20
+ JobAction.modify_job(args[0], job_value)
21
+ cache.delete('modify_' + args[0])
22
+ if get_lock(args[0]):
23
+ if args[2] == 'date' or (job_value and job_value[0] == 'date'):
24
+ JobList.objects.filter(id=int(args[1])).update(job_state=0, update_time=timezone.now())
25
+ return func(*args, **kwargs)
26
+ else:
27
+ JobAction.stop_job(args[0])
28
+ else:
29
+ JobAction.stop_job(args[0])
30
+
31
+ wrapper._is_decorated = True
32
+ return wrapper
33
+
34
+
35
+ # Job status detection
36
+ def monitor_job_status():
37
+ from autojob.job_new import JobAction
38
+ job_stop = cache.iter_keys('stop_*')
39
+ for i in job_stop:
40
+ JobAction.stop_job(cache.get(i))
41
+ job_modify = cache.iter_keys('modify_*')
42
+ for i in job_modify:
43
+ JobAction.modify_job(i.replace('modify_', ''), cache.get(i))
44
+
45
+
46
+ def get_lock(lock_name):
47
+ lock = cache.lock('lock.' + lock_name, timeout=5)
48
+ return lock.acquire(blocking=False)
49
+
50
+
51
+ def job_control():
52
+ global logger
53
+ try:
54
+ from autojob.job_new import JobAction
55
+ from autojob import job_new
56
+ from autojob.models import JobList
57
+ import logging
58
+
59
+ logger = logging.getLogger(__name__)
60
+
61
+ job_list_ = JobList.objects.filter(job_state=1)
62
+ logger.info('Program startup, start scheduled tasks : ' + str(job_list_.__len__()))
63
+ job_new.start_scheduler()
64
+ for job_ in job_list_:
65
+ if hasattr(JobAction, 'start_%s_job' % job_.action_type):
66
+ func = getattr(JobAction(), 'start_%s_job' % job_.action_type)
67
+ func(job_.trigger.trigger_func, job_.job_rate, str(job_.id))
68
+ else:
69
+ logger.error('【start error】 ' + job_.trigger.trigger_func + ' does not exists!')
70
+ except Exception as rel:
71
+ logger.error("scheduler start error:" + str(rel))
File without changes
@@ -0,0 +1,66 @@
1
+ import os
2
+ import inspect
3
+ import importlib
4
+
5
+ from django.core.management.base import BaseCommand
6
+ from django.conf import settings
7
+ from django.db.utils import IntegrityError
8
+
9
+
10
+ class Command(BaseCommand):
11
+ help = """扫描整个 Django 项目中的所有函数,查找使用了定时任务装饰器的函数,在项目初始化的时候写入对应数据表
12
+ 由于每个项目的目录不同,复杂度不同,可能出现任务扫描缺失的情况,这时就需要应用启动后手动录入"""
13
+
14
+ def handle(self, *args, **kwargs):
15
+ # 从settings中获取项目的路径
16
+ project_root = settings.BASE_DIR
17
+ # 要过滤的目录和文件
18
+ exclude_dirs = {'migrations', '__pycache__', 'static', 'media', 'templates', 'venv'}
19
+ exclude_files = {'manage.py', 'settings.py', '__init__.py', 'urls.py', 'admin.py', 'models.py'}
20
+
21
+ # 遍历整个项目目录
22
+ for root, dirs, files in os.walk(project_root):
23
+ # 过滤目录
24
+ dirs[:] = [d for d in dirs if d not in exclude_dirs]
25
+
26
+ for file in files:
27
+ if file.endswith('.py') and file not in exclude_files:
28
+ module_path = os.path.join(root, file)
29
+ self.get_module_name(module_path, project_root)
30
+
31
+ def get_module_name(self, module_path, root_path):
32
+ relative_path = os.path.relpath(module_path, root_path)
33
+ module_name = relative_path.replace(os.sep, '.')[:-3]
34
+ if module_name:
35
+ # self.stdout.write(f'正在导入模块: {module_name}')
36
+ self.import_module(module_name)
37
+
38
+ def import_module(self, module_name):
39
+ try:
40
+ module = importlib.import_module(module_name)
41
+ self.check_module_functions(module)
42
+ except ImportError as e:
43
+ # self.stdout.write(f'导入模块 {module_name} 失败: {e}')
44
+ pass
45
+
46
+ def check_module_functions(self, module):
47
+ for name, obj in inspect.getmembers(module):
48
+ if inspect.isfunction(obj) or inspect.ismethod(obj):
49
+ self._is_decorated_function(name, obj)
50
+
51
+ def _is_decorated_function(self, name, func):
52
+ if hasattr(func, '__wrapped__') and hasattr(func, '_is_decorated'):
53
+ self._insert_job_trigger(name, func)
54
+
55
+ def _insert_job_trigger(self, name, obj):
56
+ try:
57
+ from autojob.models import JobTrigger
58
+ description = inspect.getdoc(obj)
59
+ if description is None:
60
+ description = f'{obj.__module__}.{obj.__name__}'
61
+ JobTrigger.objects.create(
62
+ trigger_name=name, trigger_func=obj.__name__,
63
+ func_path=f'from {obj.__module__} import {obj.__name__}', description=description)
64
+ self.stdout.write(f'检测到新增定时任务:{obj.__module__}.{obj.__name__}')
65
+ except IntegrityError as e:
66
+ pass
@@ -0,0 +1,45 @@
1
+ # Generated by Django 3.2.25 on 2024-08-05 09:21
2
+
3
+ from django.db import migrations, models
4
+ import django.db.models.deletion
5
+
6
+
7
+ class Migration(migrations.Migration):
8
+
9
+ initial = True
10
+
11
+ dependencies = [
12
+ ]
13
+
14
+ operations = [
15
+ migrations.CreateModel(
16
+ name='JobTrigger',
17
+ fields=[
18
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
19
+ ('trigger_name', models.CharField(max_length=25, verbose_name='trigger_name')),
20
+ ('trigger_func', models.CharField(max_length=25, verbose_name='trigger_func')),
21
+ ('func_path', models.CharField(help_text='e.p.:from autojob.job_test import job_test', max_length=255, verbose_name='func_path')),
22
+ ('description', models.CharField(max_length=50, verbose_name='description')),
23
+ ],
24
+ options={
25
+ 'verbose_name_plural': '定时任务触发器',
26
+ 'index_together': {('trigger_func', 'func_path')},
27
+ },
28
+ ),
29
+ migrations.CreateModel(
30
+ name='JobList',
31
+ fields=[
32
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
33
+ ('job_name', models.CharField(max_length=25, verbose_name='job_name')),
34
+ ('action_type', models.CharField(choices=[('date', 'date'), ('cron', 'cron')], default='cron', max_length=25, verbose_name='scheduling type')),
35
+ ('job_state', models.IntegerField(choices=[(0, 'stop'), (1, 'start')], default=0, verbose_name='job status')),
36
+ ('job_rate', models.CharField(help_text='Parameter corresponding to scheduling type (execution frequency) :<br/>\n 1、date:Execute task at 1am on August 30, 2019<br/>value:2019-8-30 01:00:00 <br/>\n 2、cron:Execute tasks at 2:00 am every day(second minute hour day month week year (The parameters must \n be in this order))<br/>value:0 0 2 * * * *', max_length=50, verbose_name='frequency')),
37
+ ('time', models.IntegerField(default=0, verbose_name='number of times')),
38
+ ('update_time', models.DateTimeField(auto_now_add=True, help_text='The task status change before the time is updated<br/>\n start job: The current time must be greater than one minute from the last time it was changed<br/>\n stop job: No need to wait to restart', verbose_name='update time')),
39
+ ('trigger', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='autojob.jobtrigger')),
40
+ ],
41
+ options={
42
+ 'verbose_name_plural': '定时任务',
43
+ },
44
+ ),
45
+ ]
@@ -0,0 +1,26 @@
1
+ # Generated by Django 3.2.25 on 2024-08-07 14:23
2
+
3
+ from django.db import migrations
4
+ from django.utils import timezone
5
+
6
+
7
+ def insert_initial_data(apps, schema_editor):
8
+ # 添加初始数据
9
+ JobTrigger = apps.get_model('autojob', 'JobTrigger')
10
+ JobTrigger.objects.create(trigger_name='job-test', trigger_func='job_test',
11
+ func_path='from autojob.job_test import job_test', description='job-test')
12
+ JobList = apps.get_model('autojob', 'JobList')
13
+ JobList.objects.create(job_name='job-test-cron', action_type='cron', job_state=0, job_rate='*/10 * * * * * *',
14
+ time=0, update_time=timezone.now(), trigger_id=1)
15
+ JobList.objects.create(job_name='job-test-date', action_type='date', job_state=0, job_rate='0 0 2 * * * *',
16
+ time=0, update_time=timezone.now(), trigger_id=1)
17
+
18
+
19
+ class Migration(migrations.Migration):
20
+ dependencies = [
21
+ ('autojob', '0001_initial'),
22
+ ]
23
+
24
+ operations = [
25
+ migrations.RunPython(insert_initial_data),
26
+ ]
File without changes
@@ -0,0 +1,42 @@
1
+ from django.db import models
2
+ from django.utils import timezone
3
+
4
+
5
+ class JobTrigger(models.Model):
6
+ trigger_name = models.CharField('trigger_name', max_length=25)
7
+ trigger_func = models.CharField('trigger_func', max_length=25)
8
+ func_desc = 'e.p.:from autojob.job_test import job_test'
9
+ func_path = models.CharField('func_path', help_text=func_desc, max_length=255)
10
+ description = models.CharField('description', max_length=50)
11
+
12
+ def __str__(self):
13
+ return self.trigger_name
14
+
15
+ class Meta:
16
+ verbose_name_plural = '定时任务触发器'
17
+ unique_together = ["trigger_func", "func_path"]
18
+
19
+
20
+ class JobList(models.Model):
21
+ job_name = models.CharField('job_name', max_length=25)
22
+ trigger = models.ForeignKey(JobTrigger, on_delete=models.SET_NULL, null=True)
23
+ type_choices = (('date', 'date'), ('cron', 'cron'))
24
+ type_content = '''Parameter corresponding to scheduling type (execution frequency) :<br/>
25
+ 1、date:Execute task at 1am on August 30, 2019<br/>value:2019-8-30 01:00:00 <br/>
26
+ 2、cron:Execute tasks at 2:00 am every day(second minute hour day month week year (The parameters must
27
+ be in this order))<br/>value:0 0 2 * * * *'''
28
+ action_type = models.CharField('scheduling type', choices=type_choices, max_length=25, default='cron')
29
+ gender_choices = ((0, 'stop'), (1, 'start'),)
30
+ job_state = models.IntegerField('job status', choices=gender_choices, default=0)
31
+ job_rate = models.CharField('frequency', help_text=type_content, max_length=50)
32
+ time = models.IntegerField('number of times', default=0)
33
+ help_text_update_time = '''The task status change before the time is updated<br/>
34
+ start job: The current time must be greater than one minute from the last time it was changed<br/>
35
+ stop job: No need to wait to restart'''
36
+ update_time = models.DateTimeField('update time', auto_now_add=timezone.now(), help_text=help_text_update_time)
37
+
38
+ def __str__(self):
39
+ return self.job_name
40
+
41
+ class Meta:
42
+ verbose_name_plural = '定时任务'
@@ -0,0 +1,3 @@
1
+ from django.test import TestCase
2
+
3
+ # Create your tests here.
@@ -0,0 +1,4 @@
1
+
2
+ from django.conf.urls import url
3
+ urlpatterns = [
4
+ ]
@@ -0,0 +1,3 @@
1
+ from django.shortcuts import render
2
+
3
+ # Create your views here.
@@ -0,0 +1,117 @@
1
+ Metadata-Version: 2.1
2
+ Name: django-autojob
3
+ Version: 1.0.0
4
+ Summary: Django customizes management pages based on APScheduler
5
+ Home-page: https://github.com/lmycc/autojob
6
+ Author: zkrliumy
7
+ Author-email: zkrliumy@163.com
8
+ License: UNKNOWN
9
+ Description: # README.md
10
+ - [English](https://github.com/lmycc/autojob/blob/main/README.md)
11
+ - [简体中文](https://github.com/lmycc/autojob/blob/main/README.zh_CN.md)
12
+
13
+ # AutoJob
14
+
15
+ #### AutoJob 是整合了APScheduler和Django的一个定时任务app,只需安装依赖,通过一定配置即可完成定时任务的开发,可通过页面管理定时任务的编辑和状态变更
16
+ #### 该app解决了在 Django + uwsgi 部署应用时,启动多个进程会导致定时任务启动冲突的情况
17
+ #### 暂只支持`corn`和`date`两种类型,本地需安装redis
18
+ #### 该定时任务还适配了simple-ui前端框架
19
+
20
+ ## 安装方式
21
+ ```
22
+ pip install autojob
23
+ ```
24
+ ## 使用方式
25
+
26
+ ### 1. 添加 "autojob" 到 `settings.py`的 INSTALLED_APPS 中:
27
+ ```
28
+ INSTALLED_APPS = [
29
+ ...
30
+ 'autojob.apps.AutoJob',
31
+ ]
32
+ ```
33
+
34
+ ### 2. 执行 `python manage.py migrate autojob` 迁移数据表,下面是添加触发器的方式
35
+ #### 两种录入自定义定时任务的方式
36
+ - **终端命令方式**
37
+ ```
38
+ ## django项目中编写了自定义的定时任务后,可以在终端执行以下命令:
39
+ python manage.py scan_jobs
40
+
41
+ ##返回以下信息,即表示成功添加了定时任务触发器到数据表中(重复执行不会导致重复添加):
42
+ ###检测到新增定时任务:myapp.abc.job_test
43
+ ```
44
+ - **代码调用方式**
45
+ ```
46
+ ## 这种方式是在`wsgi.py`文件中增加对command的引用来录入自定义定时任务触发器
47
+ from app.management.commands.scan_jobs import Command
48
+ scan_jobs = Command()
49
+ scan_jobs.handle()
50
+
51
+ ##返回以下信息,即表示成功添加了定时任务触发器到数据表中(重复执行不会导致重复添加):
52
+ ###检测到新增定时任务:myapp.abc.job_test
53
+ ```
54
+
55
+ ### 3. django应用启动时调用定时任务,在 `wsgi.py`中添加:
56
+ ```
57
+ from autojob import job_tool
58
+ job_tool.job_control()
59
+ ```
60
+
61
+ ### 4. 在 `settings.py`添加redis配置
62
+ ```
63
+ CACHES = {
64
+ "default": {
65
+ "BACKEND": "django_redis.cache.RedisCache",
66
+ "LOCATION": "redis://127.0.0.1:6379/0",
67
+ "OPTIONS": {
68
+ "PICK_VERSION": -1,
69
+ "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor",
70
+ "CLIENT_CLASS": "django_redis.client.DefaultClient",
71
+ "PASSWORD": ""
72
+ }
73
+ }
74
+ }
75
+ ```
76
+
77
+ ### 5. 一个测试任务的demo: `job_test.py`
78
+
79
+ ```
80
+ # coding=utf-8
81
+ import datetime
82
+ import logging
83
+
84
+ from app.job_tool import job_before
85
+
86
+ logger = logging.getLogger(__name__)
87
+
88
+
89
+ @job_before
90
+ def job_test(*args):
91
+ # 当应用程序启动时,录入任务触发器时会读取下面这行文档当做触发器的描述,如果没有则默认描述是函数的路径
92
+ """一个测试的定时任务"""
93
+ now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
94
+ logger.info(now + '__This is a timed task for testing:' + args[0])
95
+ ```
96
+
97
+
98
+ Keywords: autojob
99
+ Platform: UNKNOWN
100
+ Classifier: Development Status :: 5 - Production/Stable
101
+ Classifier: Environment :: Web Environment
102
+ Classifier: Intended Audience :: Developers
103
+ Classifier: License :: OSI Approved :: BSD License
104
+ Classifier: Operating System :: OS Independent
105
+ Classifier: Programming Language :: Python
106
+ Classifier: Programming Language :: Python :: 3
107
+ Classifier: Programming Language :: Python :: 3.6
108
+ Classifier: Programming Language :: Python :: 3.7
109
+ Classifier: Programming Language :: Python :: 3.8
110
+ Classifier: Programming Language :: Python :: 3.9
111
+ Classifier: Programming Language :: Python :: 3.10
112
+ Classifier: Programming Language :: Python :: 3 :: Only
113
+ Classifier: Framework :: Django
114
+ Classifier: Framework :: Django :: 2
115
+ Classifier: Framework :: Django :: 3
116
+ Classifier: Framework :: Django :: 4
117
+ Description-Content-Type: text/markdown
@@ -0,0 +1,26 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ setup.py
5
+ autojob/__init__.py
6
+ autojob/admin.py
7
+ autojob/apps.py
8
+ autojob/job_new.py
9
+ autojob/job_test.py
10
+ autojob/job_tool.py
11
+ autojob/models.py
12
+ autojob/tests.py
13
+ autojob/urls.py
14
+ autojob/views.py
15
+ autojob/management/__init__.py
16
+ autojob/management/commands/__init__.py
17
+ autojob/management/commands/scan_jobs.py
18
+ autojob/migrations/0001_initial.py
19
+ autojob/migrations/0002_auto_20240807_1423.py
20
+ autojob/migrations/__init__.py
21
+ django_autojob.egg-info/PKG-INFO
22
+ django_autojob.egg-info/SOURCES.txt
23
+ django_autojob.egg-info/dependency_links.txt
24
+ django_autojob.egg-info/not-zip-safe
25
+ django_autojob.egg-info/requires.txt
26
+ django_autojob.egg-info/top_level.txt
@@ -0,0 +1,4 @@
1
+ Django>=2.0
2
+ djangorestframework>=3.7.0
3
+ APScheduler
4
+ django-redis
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,55 @@
1
+ import os
2
+
3
+ from setuptools import setup, find_packages
4
+
5
+ # with open("README.md") as f:
6
+ # long_description = f.read()
7
+
8
+ with open(os.path.join(os.path.dirname(__file__), 'README.md'), encoding='utf-8') as readme:
9
+ README = readme.read()
10
+
11
+ # allow setup.py to be run from any path
12
+ os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
13
+
14
+ setup(
15
+ name="django-autojob",
16
+ version='1.0.0',
17
+ description="Django customizes management pages based on APScheduler",
18
+ keywords='autojob',
19
+ long_description=README,
20
+ long_description_content_type="text/markdown",
21
+ author='zkrliumy',
22
+ author_email='zkrliumy@163.com',
23
+ url="https://github.com/lmycc/autojob",
24
+ include_package_data=True,
25
+ # 你要安装的包,通过 setuptools.find_packages 找到当前目录下有哪些包
26
+ packages=find_packages(include=('autojob', 'autojob.*',)),
27
+ zip_safe=False,
28
+ # 表明当前模块依赖哪些包,若环境中没有,则会从pypi中下载安装
29
+ install_requires=[
30
+ 'Django>=2.0',
31
+ 'djangorestframework>=3.7.0',
32
+ 'APScheduler',
33
+ 'django-redis',
34
+ ],
35
+
36
+ classifiers=[
37
+ "Development Status :: 5 - Production/Stable",
38
+ "Environment :: Web Environment",
39
+ "Intended Audience :: Developers",
40
+ "License :: OSI Approved :: BSD License",
41
+ "Operating System :: OS Independent",
42
+ "Programming Language :: Python",
43
+ "Programming Language :: Python :: 3",
44
+ "Programming Language :: Python :: 3.6",
45
+ "Programming Language :: Python :: 3.7",
46
+ "Programming Language :: Python :: 3.8",
47
+ "Programming Language :: Python :: 3.9",
48
+ "Programming Language :: Python :: 3.10",
49
+ "Programming Language :: Python :: 3 :: Only",
50
+ "Framework :: Django",
51
+ "Framework :: Django :: 2",
52
+ "Framework :: Django :: 3",
53
+ "Framework :: Django :: 4",
54
+ ],
55
+ )