1. 需求:添加一个定时任务可选择周期任务与定时任务,生成一个定时任务,点击生成报告 触发定时任务,点击取消生成报告删除定时任务
周期任务界面:
定时任务界面:
2.静态页面部分:
1. < div class= "inline field" > < div class= "ui checkbox" id= "cycle_checkbox_div" > < input type= "hidden" id= "timeType" ng= "formData.timeType" > < input type= "checkbox" id= "checkbox_cycleProject" name= "timeType" > < label id= "lab_cycleProject" > 周期执行</ label > </ div > < div class= "ui checkbox" id= "checkbox_timingdiv" > < input type= "checkbox" id= "checkbox_timing" name= "timeType" > < label id= "lab_timing" > 定时执行</ label > </ div > </ div > < div id= "cycle_config" class= "four fields" style= " display : flex ; " > < div id= "" class= "three widefield" > < label > 计划类型:</ label > < div class= "ui selectiondropdown" id= "cycleType_select" tabindex= "0" > < input type= "hidden" name= "cycleType" id= "cycleType" > < div class= "default text" > 计划类型</ div > < i class= "dropdownicon" ></ i > < div class= "menu transitionhidden" tabindex= "-1" > <!--<div class="item"id="for_year" data-value="year">--> <!--每年--> <!--</div>--> <%--<divclass="item" id="for_month"data-value="month">--%> <%--每月--%> <%--</div>--%> < div class= "item" id= "for_week" data-value= "week" > 每周 </ div > < div class= "item" id= "for_day" data-value= "day" > 每天 </ div > <%--<div class="item"id="for_hour" data-value="hour">--%> <%--每小时--%> <%--</div>--%> <%--<divclass="item" id="for_minute"data-value="min">--%> <%--每分钟--%> <%--</div>--%> </ div > </ div > </ div > < div id= "month" class= "three widefield" > < label > 月:</ label > < div class= "ui selectiondropdown" name= "month" id= "month_select" tabindex= "0" > < input type= "hidden" > < div class= "default text" > 月</ div > < i class= "dropdownicon" ></ i > < div class= "menu transitionhidden" tabindex= "-1" > < div class= "item" data-value= "1" > 一月 </ div > < div class= "item" data-value= "2" > 二月 </ div > < div class= "item" data-value= "3" > 三月 </ div > < div class= "item" data-value= "4" > 四月 </ div > < div class= "item" data-value= "5" > 五月 </ div > < div class= "item" data-value= "6" > 六月 </ div > < div class= "item" data-value= "7" > 七月 </ div > < div class= "item" data-value= "8" > 八月 </ div > < div class= "item" data-value= "9" > 九月 </ div > < div class= "item" data-value= "10" > 十月 </ div > < div class= "item" data-value= "11" > 十一月 </ div > < div class= "item" data-value= "12" > 十二月 </ div > </ div > </ div > </ div > < div id= "week" class= "three widefield" > < label > 周:</ label > < div class= "ui selectiondropdown" name= "week" id= "week_select" tabindex= "0" > < input type= "hidden" > < div class= "default text" > 周</ div > < i class= "dropdownicon" ></ i > < div class= "menu" tabindex= "-1" > < div class= "item" data-value= "7" > 周日 </ div > < div class= "item" data-value= "1" > 周一 </ div > < div class= "item" data-value= "2" > 周二 </ div > < div class= "item" data-value= "3" > 周三 </ div > < div class= "item" data-value= "4" > 周四 </ div > < div class= "item" data-value= "5" > 周五 </ div > < div class= "item" data-value= "6" > 周六 </ div > </ div > </ div > </ div > < div id= "day" class= "one widefield" name= "day" > < label > 日:</ label > < input placeholder= " 日" type= "text" id= "day_input" > </ div > < div id= "hour" class= "one widefield" name= "hour" > < label > 小时:</ label > < input placeholder= " 小时" type= "text" id= "hour_input" > </ div > < div id= "minute" class= "one widefield" name= "minute" > < label > 分钟:</ label > < input placeholder= " 分钟" type= "text" id= "minute_input" > </ div > </ div > < div class= "two fields" id= "timing_config" > < div class= "requiredfield" > < label > 定时时间</ label > < div class= "ui left iconinput" > < input placeholder= " 定时时间" id= "presetTime" type= "text" ng-model= "formData.presetTime" class= "noEmpty" > < i class= "calendaricon" ></ i > </ div > </ div > < div class= "requiredfield" > </ div > </ div > < div class= "actions center text-center" align= "right" style= " margin-right : - 4 px ; " >
3.js引用部分
引用:
< link rel= "stylesheet" href= "../../dist/semantic.min.css" > < script src= "../../js/jquery-2.1.4.min.js" ></ script > < script src= "../../dist/semantic.min.js" ></ script >
< link rel= "stylesheet" type= "text/css" media= "all" href= "../../plugins/daterangepicker/daterangepicker.css" /> < script type= "text/javascript" src= "../../plugins/daterangepicker/moment.js" ></ script > < script type= "text/javascript" src= "../../plugins/daterangepicker/daterangepicker.js" ></ script >
< script type= "" > time ();circleTime(); function time (){ // 注册下拉菜单 $ ( '. ui . dropdown ' ). dropdown (); $ ( '#presetTime' ). daterangepicker ({ "singleDatePicker" : true , "startDate" : new Date (), endDate : new Date (), // maxDate: new Date(), timePicker : true , timePickerSeconds : true , format : 'YYYY-MM-DD HH:mm:ss' , timePicker12Hour : false , }, function (start, end, label) { }); // 定时执行 $ ( "#checkbox_timing" ). click ( function () { console . log ( 222 ) $ ( "#checkbox_cycleProject" ). attr ( "checked" , false ); $ ( "#checkbox_timing" ). attr ( "checked" , true ); $ ( '#month_select' ). dropdown ( 'clear' ); $ ( '#week_select' ). dropdown ( 'clear' ); $ ( '#day_input' ). val ( "" ); $ ( '#hour_input' ). val ( "" ); $ ( '#minute_input' ). val ( "" ); $ ( "#cycle_config" ). hide (); var checkboxFlag = $ ( "#checkbox_timing:checkbox:checked" ). length ; if ( checkboxFlag == 1 ) { $ ( "#timing_config" ). show (); } else { $ ( "#timing_config" ). hide (); $ ( '#presetTime' ). val ( "" ); } }); // 周期执行 $ ( "#checkbox_cycleProject" ). click ( function () { $ ( "#checkbox_cycleProject" ). attr ( "checked" , true ); $ ( "#checkbox_timing" ). attr ( "checked" , false ); $ ( '#presetTime' ). val ( "" ); $ ( "#timing_config" ). hide (); var checkboxFlag = $ ( "#checkbox_cycleProject:checkbox:checked" ). length ; if ( checkboxFlag == 1 ) { $ ( "#cycle_config" ). show (); } else { $ ( "#cycle_config" ). hide (); $ ( '#month_select' ). dropdown ( 'clear' ); $ ( '#week_select' ). dropdown ( 'clear' ); $ ( '#day_input' ). val ( "" ); $ ( '#hour_input' ). val ( "" ); $ ( '#minute_input' ). val ( "" ); } }); $ ( "#cycle_config" ). hide (); $ ( "#timing_config" ). hide (); $ ( "#for_year" ). click ( function (){ $ ( "#month" ). show (); $ ( "#week" ). hide (); $ ( '#week_select' ). dropdown ( 'clear' ); $ ( "#day" ). show (); $ ( "#hour" ). show (); $ ( "#minute" ). show (); }); $ ( "#for_month" ). click ( function (){ $ ( "#month" ). hide (); $ ( '#month_select' ). dropdown ( 'clear' ); $ ( "#week" ). hide (); $ ( '#week_select' ). dropdown ( 'clear' ); $ ( "#day" ). show (); $ ( "#hour" ). show (); $ ( "#minute" ). show (); }); $ ( "#for_week" ). click ( function (){ console . log ( "year" ) $ ( "#month" ). hide (); $ ( '#month_select' ). dropdown ( 'clear' ); $ ( "#week" ). show (); $ ( "#day" ). hide (); $ ( '#day_input' ). val ( "" ); $ ( "#hour" ). show (); $ ( "#minute" ). show (); }); $ ( "#for_day" ). click ( function (){ console . log ( "year" ) $ ( "#month" ). hide (); $ ( "#week" ). hide (); $ ( "#day" ). hide (); $ ( '#month_select' ). dropdown ( 'clear' ); $ ( '#week_select' ). dropdown ( 'clear' ); $ ( '#day_input' ). val ( "" ); $ ( "#hour" ). show (); $ ( "#minute" ). show (); }); $ ( "#for_hour" ). click ( function (){ console . log ( "year" ) $ ( "#month" ). hide (); $ ( "#week" ). hide (); $ ( "#day" ). hide (); $ ( "#hour" ). hide (); $ ( '#month_select' ). dropdown ( 'clear' ); $ ( '#week_select' ). dropdown ( 'clear' ); $ ( '#day_input' ). val ( "" ); $ ( '#hour_input' ). val ( "" ); $ ( "#minute" ). show (); }); $ ( "#for_minute" ). click ( function (){ console . log ( "year" ) $ ( "#month" ). hide (); $ ( "#week" ). hide (); $ ( "#day" ). hide (); $ ( "#hour" ). hide (); $ ( "#minute" ). hide (); $ ( '#month_select' ). dropdown ( 'clear' ); $ ( '#week_select' ). dropdown ( 'clear' ); $ ( '#day_input' ). val ( "" ); $ ( '#hour_input' ). val ( "" ); $ ( '#minute_input' ). val ( "" ); }); // $("#for_now").click(function(){ // console.log("year") // $("#month").hide(); // $("#week").hide(); // $("#day").hide(); // $("#hour").hide(); // $("#minute").hide(); // // $('#month_select').dropdown('clear'); // $('#week_select').dropdown('clear'); // $('#day_input').val(""); // $('#hour_input').val(""); // $('#minute_input').val(""); // }); } function circleTime (){ // 拼接周期执行时间 var month = $ ( '#month_select' ). dropdown ( 'get value' ); var week = $ ( '#week_select' ). dropdown ( 'get value' ); var day = $ ( '#day_input' ). val (); var hour = $ ( '#hour_input' ). val (); var minute = $ ( '#minute_input' ). val (); var type = $ ( "#cycleType" ). val (); if ( month == "" ){ month = "-" ; } if ( week == "" ){ week = "-" ; } if ( day == "" ){ day = "-" ; } if ( hour == "" ){ hour = "-" ; } if ( minute == "" ){ minute = "-" ; } if ( type == "" ){ minute = "-" ; } var cycle = month + "/" + week + "/" + day + "/" + hour + "/" + minute + "/" + type ; console . log ( cycle + "rrrrr" ) return cycle ; }</ script >
4.定时任务的启动停止删除的封装类(JobManager)
package com.topsec.tsm.util; import org.quartz.*; import org.quartz.impl.StdSchedulerFactory; import java.text.ParseException; import java.util.Date; import java.util.HashMap; import java.util.Map; import static org.quartz.CronScheduleBuilder.cronSchedule ; import static org.quartz.JobBuilder.newJob ; import static org.quartz.SimpleScheduleBuilder.simpleSchedule ; import static org.quartz.TriggerBuilder.newTrigger ; /** * Created by zjx on 2017/8/23. */public class JobManager { public static final int INTERVAL = 1 ; public static final int TIMEOUT = 2 ; public static final int NOW = 3 ; public static Map<String, TriggerKey> triggerKeyMap = new HashMap<>(); public static Map<String, JobKey> jobKeyMap = new HashMap<>(); public static Map<String, CycleConfig> cycleTimeMap = new HashMap<>(); // 任务调度器 private Scheduler scheduler ; // 调度器工厂 private SchedulerFactory schedulerFactory ; // 数据监听 private JobManager() throws SchedulerException { schedulerFactory = new StdSchedulerFactory(); scheduler = schedulerFactory .getScheduler(); } public SchedulergetScheduler() { return this . scheduler ; } private static JobManager jobManager ; public static JobManager getInstance() throws SchedulerException{ if ( jobManager == null ) { synchronized ( "JobManager" ){ if ( jobManager == null ){ jobManager = new JobManager(); } } } return jobManager ; } public void resumeAll() throws SchedulerException { scheduler .resumeAll(); } public void shutdown() throws SchedulerException { scheduler .shutdown(); } public void start() throws SchedulerException { scheduler .start(); } public boolean isInStandbyMode() throws SchedulerException{ return scheduler .isInStandbyMode(); } public boolean isShutdown() throws SchedulerException { return scheduler .isShutdown(); } public boolean isStarted() throws SchedulerException { return scheduler .isStarted(); } public void pauseAll() throws SchedulerException { scheduler .pauseAll(); } public void standby() throws SchedulerException { scheduler .standby(); } public void scheduleJob(JobDetail jobDetail, CronTrigger trigger) throws SchedulerException { scheduler .scheduleJob(jobDetail, trigger); } public JobDetailgetJobDetail(String uniqueid) throws SchedulerException { return scheduler .getJobDetail(JobKey.jobKey (uniqueid,uniqueid)); } public void deleteJob(String uniqueid) throws SchedulerException { boolean result = scheduler .deleteJob(JobKey.jobKey (uniqueid,uniqueid)); if (result){ cycleTimeMap .remove(uniqueid); triggerKeyMap .remove(uniqueid); jobKeyMap .remove(uniqueid); } } public void pauseJob(String uniqueid) throws SchedulerException { scheduler .pauseJob(JobKey.jobKey (uniqueid, uniqueid)); } public void resumeJob(String uniqueid) throws SchedulerException { scheduler .resumeJob(JobKey.jobKey (uniqueid, uniqueid)); } //设置cron 表达式 public StringsetCron(CycleConfig cycleConfig) { String type =cycleConfig.gettype(); String mon =cycleConfig.getmonth(); String week =cycleConfig.getweek(); String day =cycleConfig.getday(); String hour =cycleConfig.gethour(); String min = cycleConfig.getmin(); String str = null ; if ( "year" .equals(type)) { str = "0" + "" + min + " " + hour + " " + day+ " " + mon + " " + "?" + " " + "*" ; } else if ( "month" .equals(type)) { str = "0" + "" + min + " " + hour + " " + day+ " " + "*" + "" + "?" + "" + "*" ; } else if ( "week" .equals(type)) { str = "0" + "" + min + " " + hour + " " + "?" + "" + "*" + "" + week + " " + "*" ; } else if ( "day" .equals(type)) { str = "0" + "" + min + " " + hour + " " + "*" + "" + "*" + "" + "?" + "" + "*" ; } else if ( "hour" .equals(type)) { str = "0" + "" + min + " " + "*" + " " + "*" + " " + "*" + " " + "?" + " " + "*" ; }else if ( "min" .equals(type)) { str = "0" + " " + "0/1" + " " + "*" + " " + "*" + " " + "*" + " " + "?" ; } return str; } /** * 周期任务 * @param cycleConfig * @param clazz * @throws ParseException */ public void setTask(CycleConfig cycleConfig, Class<? extends Job> clazz) throws ParseException { String str =setCron(cycleConfig); JobDetail jobDetail = newJob (clazz).withIdentity(cycleConfig.getUniqueid(),cycleConfig.getUniqueid()).build(); jobDetail.getJobDataMap().put("id" , cycleConfig.getUniqueid()); cycleTimeMap .put(cycleConfig.getUniqueid(), cycleConfig); CronScheduleBuilderscheduleBuilder = cronSchedule (str);//"0/5 * * * * ?" CronTrigger trigger = newTrigger ().withIdentity(cycleConfig.getUniqueid(),cycleConfig.getUniqueid()).withSchedule(scheduleBuilder).build(); try { scheduler .scheduleJob(jobDetail, trigger); scheduler .start(); triggerKeyMap .put(cycleConfig.getUniqueid(), trigger.getKey()); jobKeyMap .put(cycleConfig.getUniqueid(), jobDetail.getKey()); } catch (Exceptione) { e.printStackTrace(); } } /** * 定时任务 * * @param id 任务ID * @param clazz 要执行的Job * @param startTime 定时时间 * @throws org.quartz.SchedulerException * @throws ParseException */ public void setTask(String id, Class<? extends Job> clazz, Date startTime) throws SchedulerException,ParseException { JobDetail jobDetail = newJob (clazz).withIdentity(id,id).usingJobData("type" , JobManager. TIMEOUT ).build(); jobDetail.getJobDataMap().put("id" , id); Trigger trigger = newTrigger ().withSchedule(simpleSchedule ().withRepeatCount(0 )) .startAt(startTime).withIdentity(id, id).build(); scheduler .scheduleJob(jobDetail, trigger); scheduler .start(); triggerKeyMap .put(id, trigger.getKey()); } /** * 即时任务 * * @param id * @param clazz * @throws org.quartz.SchedulerException * @throws ParseException */ public void setTask(String id, Class<? extends Job> clazz) throws SchedulerException,ParseException { JobDetail jobDetail = newJob (clazz).withIdentity(id,id).usingJobData("type" , JobManager. NOW ).build(); jobDetail.getJobDataMap().put("id" , id); Trigger trigger = newTrigger ().withSchedule(simpleSchedule ().withRepeatCount(0 )) .startNow().withIdentity(id, id).build(); scheduler .scheduleJob(jobDetail, trigger); scheduler .start(); } public boolean stopTask(String projectId) throws ParseException{ TriggerKey triggerKey = null ; JobKey jobKey = null ; boolean stopFlag = true ; try { SchedulerFactorygSchedulerFactory = new StdSchedulerFactory(); Scheduler scheduler =gSchedulerFactory.getScheduler(); if ( triggerKeyMap .containsKey(projectId)) { triggerKey = triggerKeyMap .get(projectId); scheduler.pauseTrigger(triggerKey);// 停止触发器 stopFlag =scheduler.unscheduleJob(triggerKey); // 移除触发器 return stopFlag; // //判断是否找到触发器并成功停止 // if(jobKeyMap.containsKey(projectId)&& stopFlag){ // jobKey =jobKeyMap.get(projectId); // scheduler.interrupt(jobKey); // stopFlag =scheduler.interrupt(jobKey); // stopFlag =scheduler.deleteJob(jobKey);// 删除任务 // // return stopFlag; // } else { // return false; // } } } catch (Exceptione) { e.printStackTrace(); } return false ; } }
5.CycleConfig类,用来封装cron表达式的实体 类
package com.topsec.tsm.util; public class CycleConfig { private String type ; // 定时类型 private String month ; // 月份 private String week ; // 周几 private String day ; // 几号 private String hour ; // 几点 private String min ; // 第几分钟 private Integer state ; // 任务状态 private String stop ; // 是否暂停 private String uniqueid ; // 任务的唯一标实 public CycleConfig(){} public CycleConfig(Stringuniqueid, String type, String month, String week, String day, String min, int state, String stop){ this . uniqueid = uniqueid; this . type = type; this . month = month; this . week = week; this . day = day; this . min = min; this . state = state; this . stop = stop; } public StringgetUniqueid() { return uniqueid ; } public void setUniqueid(String uniqueid) { this . uniqueid = uniqueid; } public StringgetStop() { return stop ; } public void setStop(String stop) { this . stop = stop; } public Stringgettype() { return type ; } public void settype(String type) { this . type = type; } public Stringgetmonth() { return month ; } public void setmonth(String month) { this . month = month; } public Stringgetweek() { return week ; } public void setweek(String week) { this . week = week; } public Stringgetday() { return day ; } public void setday(String day) { this . day = day; } public Stringgethour() { return hour ; } public void sethour(String hour) { this . hour = hour; } public Stringgetmin() { return min ; } public void setmin(String min) { this . min = min; } public Integergetstate() { return state ; } public void setstate(Integer state) { this . state = state; } }
6.CycleProjectUtil ,实现Job的excute方法,定时任务主要逻辑放在此 处
package com.topsec.tsm.util; import com.topsec.tsm.riskReport.dao.RiskReportRecordDao; import com.topsec.tsm.riskReport.dao.RiskReportRecordManaDao; import com.topsec.tsm.riskReport.model.RiskReportManagement; import com.topsec.tsm.riskReport.model.RiskReportRecord; import com.topsec.tsm.riskReport.service.RiskReportRecordService; import com.topsec.tsm.riskReport.service.impl.RiskReportRecordServiceImpl; import org.apache.tools.ant.util.DateUtils; import org.quartz.Job; import org.quartz.JobDataMap; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; /** * Created zjx on 2018/07/10. */public class CycleProjectUtil implements Job { private RiskReportRecordService riskReportRecordService ; private RiskReportRecordManaDao riskReportRecordManaDao ; public CycleProjectUtil(){ this . riskReportRecordService = SpringUtil.getBean (RiskReportRecordService. class ); this . riskReportRecordManaDao = SpringUtil.getBean (RiskReportRecordManaDao. class ); } @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { String projectId = null ; // 获取周期模板项目ID JobDataMap dataMap =jobExecutionContext.getJobDetail().getJobDataMap(); for (Map.Entry<String,Object>entry : dataMap.entrySet()){ // 获取到设置的jobid 也是数据的主键id projectId = (String) entry.getValue(); } // 逻辑 startCycleProject(projectId); } public boolean startCycleProject(String projectId){ boolean success = false ; try { RiskReportManagementriskReportRecord=riskReportRecordManaDao .findOne(Long.parseLong (projectId)); Integertype=riskReportRecord.getType(); if (type!= null ){ riskReportRecordService .saveRiskReportRecord(type); // 打印日志报告 System. out .println(type== 1 ? " 日报" : " 周报" + " 执行时间:" +DateUtils.format ( new Date(), "YYYY-MM-DD HH:mm:ss" )); } }catch (Exceptione){ e.printStackTrace(); return success; } return true ; } }
7.SpringUtil类:通过继承
ApplicationContextAware
获取应用上下文
SpringUtil类:通过继承ApplicationContextAware 获取应用上下文
package com.topsec.tsm.util; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype. Component ; @Component public class SpringUtil implements ApplicationContextAware { private static ApplicationContext applicationContext ; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (SpringUtil. applicationContext == null ) { SpringUtil.applicationContext = applicationContext; } } // 获取applicationContext public static ApplicationContext getApplicationContext() { return applicationContext ; } // 通过name 获取 Bean. public static Object getBean(String name) { return getApplicationContext ().getBean(name); } // 通过class 获取Bean. public static < T > T getBean(Class< T > clazz) { return getApplicationContext ().getBean(clazz); } // 通过name, 以及Clazz返回指定的Bean public static < T > T getBean(String name, Class< T > clazz) { return getApplicationContext ().getBean(name, clazz); } }
8.相当于服务层代码
package com.topsec.tsm.util; import org.quartz.SchedulerException; import java.text.ParseException; import java.text.SimpleDateFormat; /** * Created by zjx on 2018/07/10. */public class TaskUtil { /** * 设置并开始任务 * * @param id 任务id 也是主键id * @param timeType 执行类型:1: 周期 2:定时 * @param cycles 周期设置 * @param presetTime 定时时间 */ public static void setAndStartTask(Long id, int timeType, String cycles, String presetTime) { JobManager jobManager = null ; try { jobManager = JobManager.getInstance(); } catch (SchedulerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } // 设定定时器的参数 if (timeType == 2 ) { // 获取定期时间 //设定周期的场合 try { jobManager.setTask(id.toString(), CycleProjectUtil.class , new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ).parse(presetTime)); } catch (ParseException e) { e.printStackTrace(); } catch (SchedulerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } else { // 设置周期时间 CycleConfig cycleConfig = new CycleConfig(); String[] cycle = cycles.split("/" ); cycleConfig.setmonth(cycle[0 ]); cycleConfig.setweek(cycle[1 ]); cycleConfig.setday(cycle[2 ]); cycleConfig.sethour(cycle[3 ]); cycleConfig.setmin(cycle[4 ]); cycleConfig.settype(cycle[5 ]); cycleConfig.setUniqueid(id.toString()); try { jobManager.setTask(cycleConfig, CycleProjectUtil.class ); } catch (ParseException e) { e.printStackTrace(); } } } /** * 删除任务 * * @param id 任务id 也是主键id */ public static void deleteJob(Long id) { JobManager jobManager = null ; try { jobManager = JobManager.getInstance(); jobManager.deleteJob(id.toString()); } catch (SchedulerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
9.Controller层使用:
package com.topsec.tsm.util; import org.quartz.SchedulerException; import java.text.ParseException; import java.text.SimpleDateFormat; /** * Created by zjx on 2018/07/10. */public class TaskUtil { /** * 设置并开始任务 * * @param id 任务id 也是主键id * @param timeType 执行类型:1: 周期 2:定时 * @param cycles 周期设置 * @param presetTime 定时时间 */ public static void setAndStartTask(Long id, int timeType, String cycles, String presetTime) { JobManager jobManager = null ; try { jobManager = JobManager.getInstance(); } catch (SchedulerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } // 设定定时器的参数 if (timeType == 2 ) { // 获取定期时间 //设定周期的场合 try { jobManager.setTask(id.toString(), CycleProjectUtil.class , new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ).parse(presetTime)); } catch (ParseException e) { e.printStackTrace(); } catch (SchedulerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } else { // 设置周期时间 CycleConfig cycleConfig = new CycleConfig(); String[] cycle = cycles.split("/" ); cycleConfig.setmonth(cycle[0 ]); cycleConfig.setweek(cycle[1 ]); cycleConfig.setday(cycle[2 ]); cycleConfig.sethour(cycle[3 ]); cycleConfig.setmin(cycle[4 ]); cycleConfig.settype(cycle[5 ]); cycleConfig.setUniqueid(id.toString()); try { jobManager.setTask(cycleConfig, CycleProjectUtil.class ); } catch (ParseException e) { e.printStackTrace(); } } } /** * 删除任务 * * @param id 任务id 也是主键id */ public static void deleteJob(Long id) { JobManager jobManager = null ; try { jobManager = JobManager.getInstance(); jobManager.deleteJob(id.toString()); } catch (SchedulerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
if (status == 1 ) { // 执行任务 TaskUtil.setAndStartTask (did, timeType, cicle,press); } else { // 删除任务 TaskUtil.deleteJob (did); }
10.
package com.topsec.tsm.util; import org.quartz.SchedulerException; import java.text.ParseException; import java.text.SimpleDateFormat; /** * Created by zjx on 2018/07/10. */public class TaskUtil { /** * 设置并开始任务 * * @param id 任务id 也是主键id * @param timeType 执行类型:1: 周期 2:定时 * @param cycles 周期设置 * @param presetTime 定时时间 */ public static void setAndStartTask(Long id, int timeType, String cycles, String presetTime) { JobManager jobManager = null ; try { jobManager = JobManager.getInstance(); } catch (SchedulerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } // 设定定时器的参数 if (timeType == 2 ) { // 获取定期时间 //设定周期的场合 try { jobManager.setTask(id.toString(), CycleProjectUtil.class , new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ).parse(presetTime)); } catch (ParseException e) { e.printStackTrace(); } catch (SchedulerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } else { // 设置周期时间 CycleConfig cycleConfig = new CycleConfig(); String[] cycle = cycles.split("/" ); cycleConfig.setmonth(cycle[0 ]); cycleConfig.setweek(cycle[1 ]); cycleConfig.setday(cycle[2 ]); cycleConfig.sethour(cycle[3 ]); cycleConfig.setmin(cycle[4 ]); cycleConfig.settype(cycle[5 ]); cycleConfig.setUniqueid(id.toString()); try { jobManager.setTask(cycleConfig, CycleProjectUtil.class ); } catch (ParseException e) { e.printStackTrace(); } } } /** * 删除任务 * * @param id 任务id 也是主键id */ public static void deleteJob(Long id) { JobManager jobManager = null ; try { jobManager = JobManager.getInstance(); jobManager.deleteJob(id.toString()); } catch (SchedulerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
10. 注意,光这样会出现一个问题,就是系统一重启动,job储存的信息就会丢失,为此我们需要在系统初始化的时候重新设定定时任务
package com.topsec.tsm.util; import org.quartz.SchedulerException; import java.text.ParseException; import java.text.SimpleDateFormat; /** * Created by zjx on 2018/07/10. */ public class TaskUtil { /** * 设置并开始任务 * * @param id 任务id 也是主键id * @param timeType 执行类型:1:周期 2:定时 * @param cycles 周期设置 * @param presetTime 定时时间 */ public static void setAndStartTask(Long id, int timeType, String cycles, String presetTime) { JobManager jobManager = null; try { jobManager = JobManager.getInstance(); } catch (SchedulerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } //设定定时器的参数 if (timeType == 2) { //获取定期时间 //设定周期的场合 try { jobManager.setTask(id.toString(), CycleProjectUtil.class, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(presetTime)); } catch (ParseException e) { e.printStackTrace(); } catch (SchedulerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } else { //设置周期时间 CycleConfig cycleConfig = new CycleConfig(); String[] cycle = cycles.split("/"); cycleConfig.setmonth(cycle[0]); cycleConfig.setweek(cycle[1]); cycleConfig.setday(cycle[2]); cycleConfig.sethour(cycle[3]); cycleConfig.setmin(cycle[4]); cycleConfig.settype(cycle[5]); cycleConfig.setUniqueid(id.toString()); try { jobManager.setTask(cycleConfig, CycleProjectUtil.class); } catch (ParseException e) { e.printStackTrace(); } } } /** * 删除任务 * * @param id 任务id 也是主键id */ public static void deleteJob(Long id) { JobManager jobManager = null; try { jobManager = JobManager.getInstance(); jobManager.deleteJob(id.toString()); } catch (SchedulerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }
1. package com.topsec.tsm.baseConfig.config;import com.topsec.tsm.riskReport.dao.RiskReportRecordManaDao;import com.topsec.tsm.riskReport.model.RiskReportManagement;import com.topsec.tsm.util.TaskUtil;import org.springframework.beans.factory.annotation.Autowired ;import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component ;import java.util.List;/** * Created by zjx on 2017/8/23. */ @Component public class StartRunner implements CommandLineRunner { /** * 周报日报任务管理 */ private RiskReportRecordManaDao riskReportRecordManaDao ; @Autowired public StartRunner(RiskReportRecordManaDaoriskReportRecordManaDao) { this .riskReportRecordManaDao = riskReportRecordManaDao; } //继承自CommandLineRunner的run方法, CommandLineRunner、ApplicationRunner 接口是在容器启动成功后的最后一步回调(类似开机自启动)。不同点是前者是原始参数,后者框架有进一步的封装,args的参数配置如下图
@Override public void
run(String... args)
throws
Exception {
// 获取任务列表
List<RiskReportManagement> list =
riskReportRecordManaDao
.list();
for
(RiskReportManagementrs : list) {
// 如果是开始任务状态,则在项目初始化时就重新开始job
if
(rs.getStatus() ==
1
) {
// 执行任务,线程jdk8 Lambda 表达式
new
Thread(() -> TaskUtil.setAndStartTask (
rs
.getId(),
rs
.getCustom12(),
rs
.getModel1(),
rs
.getModel2())).start(); }
}
}
}
参考文档:https://blog.csdn.net/maosijunzi/article/details/42008779