項目的public文件夾下創(chuàng)建job.py文件
具體完成定時任務的創(chuàng)建喳整、運行洼怔、暫停涩馆、刪除操作
from public.log import *
from tasks import sched
from public.utils import import_method,task_time
class Job(object):
def __init__(self,task_name):
self.task_name = task_name
# 添加定時任務并啟動
def add_cron_task(self,func,schedule):
flag = 1
try:
func = import_method(func)
job = func
schedule = task_time(schedule)
secends = schedule[0]
minutes = schedule[1]
hours = schedule[2]
month = schedule[3]
dayofweek = schedule[4]
sched.add_job(job, 'cron',second=secends,minute=minutes,hour=hours,day_of_week=dayofweek,month=month, id = self.task_name)
writeLog_info('[定時任務:%s],添加成功' % (self.task_name))
flag = 0
except Exception as e:
writeLog_error('[定時任務:%s],添加失敗:%s' % (self.task_name, str(e)))
return flag
# 暫停任務
def pause_cron_task(self):
flag = 1
try:
sched.pause_job(self.task_name)
writeLog_info('[定時任務:%s],暫停成功' % (self.task_name))
flag = 0
except Exception as e:
writeLog_error('[定時任務:%s],暫停失斕躺场:%s' % (self.task_name, str(e)))
return flag
# 恢復任務
def resume_cron_task(self):
flag = 1
try:
sched.resume_job(self.task_name)
writeLog_info('[定時任務:%s],重啟成功' % (self.task_name))
flag = 0
except Exception as e:
writeLog_error('[定時任務:%s],重啟失斊ゲ恪:%s' % (self.task_name, str(e)))
return flag
# 移除任務
def remove_cron_task(self):
flag = 1
try:
sched.remove_job(self.task_name)
writeLog_info('[定時任務:%s],刪除成功' % (self.task_name))
flag = 0
except Exception as e:
writeLog_error('[定時任務:%s],刪除失敗:%s' % (self.task_name, str(e)))
return flag
#判斷當前是否有運行中的定時任務
def is_exsit_task():
flag = 1
try:
tasks = sched.get_jobs()
if tasks:
flag = 0
writeLog_info('當前運行中的定時任務:%s' % (tasks))
else:
flag = 1
writeLog_info('暫無運行中的定時任務,需要手動開啟')
except Exception as e:
writeLog_error('定時任務獲取失斝啃睢:%s'%(str(e)))
return flag
這里在public/utils中寫了兩個數(shù)據(jù)處理方法import_method,task_time
#定時任務函數(shù)引用處理
def import_method(resource):
resource = resource.split('.')
moduel_name = resource[0]
class_name = resource[1]
method_name = resource[2]
moduel =importlib.import_module(moduel_name+'.'+class_name)
c = getattr(moduel,class_name)
method = getattr(c(),method_name)
return method
#定時任務執(zhí)行時間處理
def task_time(time):
time_list = time.strip(',').split(',')
return time_list
項目下新建tasks APP
models.py中將任務寫入數(shù)據(jù)庫
from django.db import models
# Create your models here.
class Task(models.Model):
task_name = models.CharField(max_length=32,verbose_name=u'任務名稱',default="",primary_key=True)
task_method = models.CharField(max_length=20,verbose_name=u'調用方法',default="")
task_des = models.CharField(max_length=200,verbose_name=u'任務描述',default="")
task_schedule = models.CharField(max_length=20,verbose_name=u'執(zhí)行計劃',default="")
status = models.IntegerField(choices = ((0,u'運行中'),(1,u'未開啟')),default=0, verbose_name=u'項目狀態(tài)')
update_time = models.DateTimeField(auto_now=True, verbose_name=u'更新時間')
create_time = models.DateTimeField(auto_now_add=True, verbose_name=u'創(chuàng)建時間')
class Meta:
verbose_name =u'定時任務'
verbose_name_plural = verbose_name
def __str__(self):
return self.task_name
tasks APP的init.py文件
default_app_config = 'tasks.apps.TasksConfig'
from apscheduler.schedulers.background import BackgroundScheduler
sched=BackgroundScheduler()
sched.start()
tasks APP的taskviews.py文件
# _*_ encoding:utf-8 _*_
from django.shortcuts import redirect, reverse
from django.shortcuts import HttpResponse
from public.job import *
import json
from .models import Task
from public.utils import *
# 定時任務列表
@login_Check
def task(request):
try:
is_exsit_task()
tasks = Task.objects.all()
writeLog_info("定時任務列表:%s" % tasks)
return render(request, "../templates/tasks/task.html", {'tasks': tasks})
except Exception as e:
writeLog_info("定時任務列表獲取失斏ぁ:%s" % str(e))
# 定時任務創(chuàng)建
@login_Check
def add_task(request):
if request.method == 'POST':
task_name = request.POST.get("task_name")
task_method = request.POST.get("task_method")
task_des = request.POST.get("task_des")
task_schedule = request.POST.get("task_schedule")
isRepeat = len(Task.objects.filter(task_name=task_name).values())
# 不重復則新增數(shù)據(jù)
if isRepeat == 0:
try:
job = Job(task_name)
if (job.add_cron_task(task_method, task_schedule)) == 0:
Task.objects.create(task_name=task_name, task_method=task_method, task_des=task_des,
task_schedule=task_schedule)
writeLog_info(u"定時任務[%s],創(chuàng)建成功" % (task_name))
except Exception as e:
writeLog_error(u"定時任務創(chuàng)建失敗" % (str(e)))
tasks = Task.objects.all()
return render(request, "../templates/tasks/task.html", {'tasks': tasks,'isRepeat':isRepeat})
# 修改:任務回顯
@login_Check
def show_task(request):
if request.method == 'POST':
task_name = request.POST.get("task_name")
task_obj = Task.objects.get(task_name=task_name)
task_method = task_obj.task_method
task_des = task_obj.task_des
task_schedule = task_obj.task_schedule
return HttpResponse(json.dumps({
"task_name":task_name,
"task_method": task_method,
"task_des": task_des,
"task_schedule": task_schedule,
}))
return redirect(reverse(task))
# 定時任務修改
@login_Check
def modify_task(request):
if request.method == 'POST':
task_name = request.POST.get("task_name")
task_method = request.POST.get("task_method")
task_des = request.POST.get("task_des")
task_schedule = request.POST.get("task_schedule")
status = 0
try:
job = Job(task_name)
if (job.remove_cron_task()) == 0:
Task.objects.filter(task_name=task_name).delete()
if (job.add_cron_task(task_method, task_schedule)) == 0:
Task.objects.filter(task_name=task_name).update(task_method=task_method, task_des=task_des,
task_schedule=task_schedule,status=status)
writeLog_info(u"定時任務[%s]瘸爽,更新成功" % (task_name))
else:
writeLog_error(u"定時任務[%s]您访,更新失敗" % (task_name))
else:
if (job.add_cron_task(task_method, task_schedule)) == 0:
Task.objects.filter(task_name=task_name).update(task_method=task_method, task_des=task_des,
task_schedule=task_schedule,status=status)
writeLog_info(u"定時任務[%s],更新成功" % (task_name))
else:
writeLog_error(u"定時任務[%s]剪决,更新失敗" % (task_name))
except Exception as e:
writeLog_error(u"定時任務[%s]灵汪,更新失斕囱怠:%s" % (task_name,str(e)))
return redirect(reverse(task))
# 定時任務暫停
@login_Check
def pause_task(request):
if request.method == 'POST':
task_name = request.POST.get("task_name")
try:
job = Job(task_name)
if (job.pause_cron_task()) == 0:
Task.objects.filter(task_name=task_name).update(status=1)
writeLog_info(u"定時任務[%s],暫停成功" % (task_name))
else:
Task.objects.filter(task_name=task_name).update(status=1)
writeLog_info(u"定時任務[%s]享言,暫停成功" % (task_name))
return redirect(reverse(task))
except Exception as e:
writeLog_error(u"定時任務暫停失敗" % (str(e)))
return redirect(reverse(task))
# 定時任務重啟
@login_Check
def restart_task(request):
if request.method == 'POST':
task_name = request.POST.get("task_name")
try:
job = Job(task_name)
if (job.resume_cron_task()) == 0:
Task.objects.filter(task_name=task_name).update(status=0)
writeLog_info(u"定時任務[%s]峻凫,重啟成功" % (task_name))
else:
obj = Task.objects.get(task_name=task_name)
task_method = obj.task_method
task_schedule = obj.task_schedule
job.add_cron_task(task_method, task_schedule)
Task.objects.filter(task_name=task_name).update(status = 0)
writeLog_info(u"定時任務[%s],重啟成功" % (task_name))
return redirect(reverse(task))
except Exception as e:
writeLog_error(u"定時任務重啟失敗" % (str(e)))
return redirect(reverse(task))
# 定時任務刪除
@login_Check
def remove_task(request):
if request.method == 'POST':
task_name = request.POST.get("task_name")
try:
job = Job(task_name)
if (job.remove_cron_task()) == 0:
Task.objects.filter(task_name=task_name).delete()
else:
Task.objects.filter(task_name=task_name).delete()
writeLog_info(u"定時任務[%s]览露,刪除成功" % (task_name))
except Exception as e:
writeLog_error(u"定時任務刪除失敗" % (str(e)))
return redirect(reverse(task))
tasks APP下的utls.py文件中添加路由分發(fā)
# _*_ coding:utf-8 _*_
__author__ = 'jessy'
__date__ = '2018/12/18 14:48'
from django.conf.urls import url
from . import taskviews
urlpatterns = [
url('^taskinfo/$', taskviews.task),
url('^taskinfo/add_task/$', taskviews.add_task),
url('^taskinfo/show_task/$', taskviews.show_task),
url('^taskinfo/modify_task/$', taskviews.modify_task),
url('^taskinfo/pause_task/$', taskviews.pause_task),
url('^taskinfo/restart_task/$', taskviews.restart_task),
url('^taskinfo/remove_task/$', taskviews.remove_task),
]
templates/task文件夾下添加task.html文件
<!DOCTYPE html>
<html lang="en">
<head>
{% load bootstrap3 %}
<title>Tasks</title>
<script src="/static/bootstrap/js/jquery.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
<link rel="stylesheet" href="/static/frame/layui/css/layui.css">
<link rel="stylesheet" href="/static/frame/static/css/style.css">
<script>
$(function () {
funisRepeat();
});
function funisRepeat() {
var isRepeat;
isRepeat = "{{ isRepeat }}";
if (isRepeat == 1) {
alert("任務名稱重復!");
}
}
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
//定時任務暫停
function pauseTask(task_name) {
//alert(id);
if (!confirm("確認要暫停:" + task_name + " 嗎?")) {
return
}
$.ajax({
url: '/task/taskinfo/pause_task/',
type: 'POST',
data: {'task_name': task_name},
beforeSend: function (xhr, settings) {
var csrftoken = getCookie('csrftoken');
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
success: function (arg) {
alert("暫停成功蔚晨!")
window.location.reload();
}
})
}
//定時任務重啟
function restartTask(task_name) {
//alert(id);
if (!confirm("確認要重啟:" + task_name + " 嗎?")) {
return
}
$.ajax({
url: '/task/taskinfo/restart_task/',
type: 'POST',
data: {'task_name': task_name},
beforeSend: function (xhr, settings) {
var csrftoken = getCookie('csrftoken');
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
success: function (arg) {
alert("重啟成功!")
window.location.reload();
}
})
}
// 用戶信息回顯
function showTask(task_name) {
//alert(task_name);
$.ajax({
url: '/task/taskinfo/show_task/',
type: 'POST',
data: {'task_name': task_name},
beforeSend: function (xhr, settings) {
var csrftoken = getCookie('csrftoken');
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
success: function (data) {
//alert(data);
var parseJson = jQuery.parseJSON(data)
$("#task_name_show").val(parseJson.task_name);
$("#task_method_show").val(parseJson.task_method);
$("#task_des_show").val(parseJson.task_des);
$('#task_schedule_show').val(parseJson.task_schedule);
$('#task_editMyModal').modal("show");
},
})
}
// 定時任務刪除
function removeTask(task_name) {
//alert(id);
if (!confirm("確認要刪除:" + task_name + " 嗎?")) {
return
}
$.ajax({
url: '/task/taskinfo/remove_task/',
type: 'POST',
data: {'task_name': task_name},
beforeSend: function (xhr, settings) {
var csrftoken = getCookie('csrftoken');
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
success: function (arg) {
alert("刪除成功肛循!")
window.location.reload();
}
})
}
</script>
</head>
<body role="document">
<!--定時任務列表-->
<div style="padding-top:20px;">
<div class="layui-row layui-col-space15">
<div class="layui-col-md10">
<!--按鈕-->
<div class="btn-group">
<button id="btn1" class="layui-btn btn " data-toggle="modal" data-target="#task_addMyModal">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>定時任務
</button>
</div>
<!--用戶列表-->
<div style="padding-top:10px">
<div>
<table id="table" table class="layui-table" lay-skin="line">
<thead>
<tr>
<th hidden>任務id</th>
<th>任務名稱</th>
<th>方法</th>
<th>描述</th>
<th>執(zhí)行計劃</th>
<th>狀態(tài)</th>
<th> 操作</th>
</tr>
</thead>
<tbody>
{% for task in tasks %}
<tr>
<td class="list" hidden>{{ task.id }}</td>
<td class="list" width="180">{{ task.task_name }}</td>
<td class="list" width="180">{{ task.task_method }}</td>
<td class="list" width="180">{{ task.task_des }}</td>
<td class="list" width="180">{{ task.task_schedule }}</td>
<td class="list" width="180">
{% if task.status == 1 %}
<a style="color:red">{{ task.get_status_display }}</a>
{% else %}
<a style="color:yellowgreen">{{ task.get_status_display }}</a>
{% endif %}
</td>
<td class="list" width="250">
{% if task.status == 1 %}
<a id="task_start" href="javascript:void(0)"
onclick="restartTask('{{ task.task_name }}')">
<img src="/static/admin/img/icon-yes.svg">重啟</a>
<a id="task_modify" href="javascript:void(0)"
onclick="showTask('{{ task.task_name }}')">
<img src="/static/admin/img/icon-changelink.svg">修改</a>
<a href="javascript:void(0)"
onclick="removeTask('{{ task.task_name }}')">
<img src="/static/admin/img/icon-deletelink.svg">刪除
</a>
{% else %}
<a id="task_pause" href="javascript:void(0)"
onclick="pauseTask('{{ task.task_name }}')">
<img src="/static/admin/img/icon-alert.svg">暫停</a>
<a href="javascript:void(0)"
onclick="removeTask('{{ task.task_name }}')">
<img src="/static/admin/img/icon-deletelink.svg">刪除
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<!-- 模態(tài)框示例(Modal) -->
<!-- 新增定時任務-->
<div class="modal fade" id="task_addMyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog" style="max-width:800px">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
<h3 class="modal-title" id="myModalLabel">
<p style="font-size: medium">新增定時任務</p>
</h3>
</div>
<div class="modal-body">
<form id='addMenu' role="form" method='POST' action="/task/taskinfo/add_task/">
<div class="form-group">
<label for="task_name">任務名稱</label>
<input type="text" class="form-control" name="task_name" placeholder="請輸入任務名稱" required
maxlength="32">
</div>
<div class="form-group">
<label for="task_method">調用方法</label>
<input type="text" class="form-control" name="task_method" placeholder="請輸入調用方法" required
maxlength="20">
</div>
<div class="form-group">
<label for="task_des">描述</label>
<input type="text" class="form-control" name="task_des" placeholder="請輸入描述信息" required
maxlength="200">
</div>
<div class="form-group">
<label for="task_schedule">執(zhí)行計劃(秒,分银择,小時多糠,月,天/周)</label>
<input type="text" class="form-control" name="task_schedule"
placeholder="請輸入執(zhí)行計劃(例:*/10,*,*,*,*)" maxlength="20">
</div>
<div class="modal-footer">
<button type="button" class="btn layui-btn" data-dismiss="modal">關閉
</button>
<button type="submit" class="btn layui-btn">
提交
</button>
</div>
{% csrf_token %}
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
<!-- 修改定時任務-->
<div class="modal fade" id="task_editMyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog" style="max-width:800px">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
<h3 class="modal-title" id="myModalLabel">
<p style="font-size: medium">定時任務修改</p>
</h3>
</div>
<div class="modal-body">
<form id='modifyMenu' role="form" method='POST' action="/task/taskinfo/modify_task/">
<div class="form-group" style="display: none">
<label for="id">id</label>
<input id="user_id" type="text" class=" form-control" name="id" placeholder="請輸入id">
</div>
<div class="form-group">
<label for="task_name">任務名稱</label>
<input id="task_name_show" type="text" class="form-control" name="task_name" required
maxlength="32" readonly="readonly">
</div>
<div class="form-group">
<label for="task_method">調用方法</label>
<input id="task_method_show" type="text" class="form-control" name="task_method"
placeholder="請輸入調用方法" required maxlength="20">
</div>
<div class="form-group">
<label for="task_des">描述</label>
<input id="task_des_show" type="text" class="form-control" name="task_des" placeholder="請輸入描述信息"
required maxlength="200">
</div>
<div class="form-group">
<label for="task_schedule">執(zhí)行計劃(秒浩考,分夹孔,小時,月析孽,天/周)</label>
<input id="task_schedule_show" type="text" class="form-control" name="task_schedule"
placeholder="請輸入執(zhí)行計劃(例:*/10,*,*,*,*)" maxlength="20">
</div>
<div class="modal-footer">
<button type="button" class="btn layui-btn" data-dismiss="modal">關閉
</button>
<button type="submit" class="btn layui-btn">
提交
</button>
</div>
{% csrf_token %}
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
</body>
</html>