动态添加、修改和删除定时任务

之前用到了定时任务,而且要求是可以动态修改定时时间,但是不要重启服务器,查了一些资料,找到了很好的一种方法,下面直接上代码。

uartzManager.java 动态添加、修改和删除定时任务管理类

  1 package com.datcent.downloadCSV.quartzManager;
  2 
  3 import org.quartz.CronTrigger ;
  4 import org.quartz.JobDetail ;
  5 import org.quartz.Scheduler ;
  6 
  7 /**
  8  * @author 作者xujingyang. E-mail:xjy06@foxmail.com
  9  * @version 创建时间:2018年1月17日 下午3:28:14
 10  * @类说明: Quartz调度管理器
 11  */
 12 public class QuartzManager {
 13     private static String JOB_GROUP_NAME = "EXTJWEB_JOBGROUP_NAME";
 14     private static String TRIGGER_GROUP_NAME = "EXTJWEB_TRIGGERGROUP_NAME";
 15 
 16     /**
 17      * @Description: 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
 18      * 
 19      * @param sched
 20      *            调度器
 21      * 
 22      * @param jobName
 23      *            任务名
 24      * @param cls
 25      *            任务
 26      * @param time
 27      *            时间设置,参考quartz说明文档
 28      * 
 29      * @Title: QuartzManager.java
 30      */
 31     public static void addJob(Scheduler sched, String jobName, @SuppressWarnings("rawtypes") Class cls, String time) {
 32         try {
 33             JobDetail jobDetail = new JobDetail(jobName, JOB_GROUP_NAME, cls);// 任务名,任务组,任务执行类
 34             // 触发器
 35             CronTrigger trigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME);// 触发器名,触发器组
 36             trigger.setCronExpression(time);// 触发器时间设定
 37             sched.scheduleJob(jobDetail, trigger);
 38             // 启动
 39             if (!sched.isShutdown()) {
 40                 sched.start();
 41             }
 42         } catch (Exception e) {
 43             throw new RuntimeException(e);
 44         }
 45     }
 46 
 47     /**
 48      * @Description: 添加一个定时任务
 49      * 
 50      * @param sched
 51      *            调度器
 52      * 
 53      * @param jobName
 54      *            任务名
 55      * @param jobGroupName
 56      *            任务组名
 57      * @param triggerName
 58      *            触发器名
 59      * @param triggerGroupName
 60      *            触发器组名
 61      * @param jobClass
 62      *            任务
 63      * @param time
 64      *            时间设置,参考quartz说明文档
 65      * 
 66      * @Title: QuartzManager.java
 67      */
 68     public static void addJob(Scheduler sched, String jobName, String jobGroupName, String triggerName,
 69             String triggerGroupName, @SuppressWarnings("rawtypes") Class jobClass, String time) {
 70         try {
 71             JobDetail jobDetail = new JobDetail(jobName, jobGroupName, jobClass);// 任务名,任务组,任务执行类
 72             // 触发器
 73             CronTrigger trigger = new CronTrigger(triggerName, triggerGroupName);// 触发器名,触发器组
 74             trigger.setCronExpression(time);// 触发器时间设定
 75             sched.scheduleJob(jobDetail, trigger);
 76         } catch (Exception e) {
 77             throw new RuntimeException(e);
 78         }
 79     }
 80 
 81     /**
 82      * @Description: 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)
 83      * 
 84      * @param sched
 85      *            调度器
 86      * @param jobName
 87      * @param time
 88      * 
 89      * @Title: QuartzManager.java
 90      */
 91     @SuppressWarnings("rawtypes")
 92     public static void modifyJobTime(Scheduler sched, String jobName, String time) {
 93         try {
 94             CronTrigger trigger = (CronTrigger) sched.getTrigger(jobName, TRIGGER_GROUP_NAME);
 95             if (trigger == null) {
 96                 return;
 97             }
 98             String oldTime = trigger.getCronExpression();
 99             if (!oldTime.equalsIgnoreCase(time)) {
100                 JobDetail jobDetail = sched.getJobDetail(jobName, JOB_GROUP_NAME);
101                 Class objJobClass = jobDetail.getJobClass();
102                 removeJob(sched, jobName);
103                 addJob(sched, jobName, objJobClass, time);
104             }
105         } catch (Exception e) {
106             throw new RuntimeException(e);
107         }
108     }
109 
110     /**
111      * @Description: 修改一个任务的触发时间
112      * 
113      * @param sched
114      *            调度器 *
115      * @param sched
116      *            调度器
117      * @param triggerName
118      * @param triggerGroupName
119      * @param time
120      * 
121      * @Title: QuartzManager.java
122      */
123     public static void modifyJobTime(Scheduler sched, String triggerName, String triggerGroupName, String time) {
124         try {
125             CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerName, triggerGroupName);
126             if (trigger == null) {
127                 return;
128             }
129             String oldTime = trigger.getCronExpression();
130             if (!oldTime.equalsIgnoreCase(time)) {
131                 CronTrigger ct = (CronTrigger) trigger;
132                 // 修改时间
133                 ct.setCronExpression(time);
134                 // 重启触发器
135                 sched.resumeTrigger(triggerName, triggerGroupName);
136             }
137         } catch (Exception e) {
138             throw new RuntimeException(e);
139         }
140     }
141 
142     /**
143      * @Description: 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
144      * 
145      * @param sched
146      *            调度器
147      * @param jobName
148      * 
149      * @Title: QuartzManager.java
150      */
151     public static void removeJob(Scheduler sched, String jobName) {
152         try {
153             sched.pauseTrigger(jobName, TRIGGER_GROUP_NAME);// 停止触发器
154             sched.unscheduleJob(jobName, TRIGGER_GROUP_NAME);// 移除触发器
155             sched.deleteJob(jobName, JOB_GROUP_NAME);// 删除任务
156         } catch (Exception e) {
157             throw new RuntimeException(e);
158         }
159     }
160 
161     /**
162      * @Description: 移除一个任务
163      * 
164      * @param sched
165      *            调度器
166      * @param jobName
167      * @param jobGroupName
168      * @param triggerName
169      * @param triggerGroupName
170      * 
171      * @Title: QuartzManager.java
172      */
173     public static void removeJob(Scheduler sched, String jobName, String jobGroupName, String triggerName,
174             String triggerGroupName) {
175         try {
176             sched.pauseTrigger(triggerName, triggerGroupName);// 停止触发器
177             sched.unscheduleJob(triggerName, triggerGroupName);// 移除触发器
178             sched.deleteJob(jobName, jobGroupName);// 删除任务
179         } catch (Exception e) {
180             throw new RuntimeException(e);
181         }
182     }
183 
184     /**
185      * @Description:启动所有定时任务
186      * 
187      * @param sched
188      *            调度器
189      * 
190      * @Title: QuartzManager.java
191      */
192     public static void startJobs(Scheduler sched) {
193         try {
194             sched.start();
195         } catch (Exception e) {
196             throw new RuntimeException(e);
197         }
198     }
199 
200     /**
201      * @Description:关闭所有定时任务
202      * 
203      * 
204      * @param sched
205      *            调度器
206      * 
207      * 
208      * @Title: QuartzManager.java
209      */
210     public static void shutdownJobs(Scheduler sched) {
211         try {
212             if (!sched.isShutdown()) {
213                 sched.shutdown();
214             }
215         } catch (Exception e) {
216             throw new RuntimeException(e);
217         }
218     }
219 }
View Code

 

Job任务类:

 

 1 package com.datcent.downloadCSV.quartzJob;
 2 
 3 import java.text.SimpleDateFormat ;
 4 import java.util.Date ;
 5 import org.apache.log4j.Logger ;
 6 import org.quartz.Job ;
 7 import org.quartz.JobExecutionContext ;
 8 import org.quartz.JobExecutionException ;
 9 import com.datcent.downloadCSV.download.CSVDownload ;
10 
11 /**
12  * @author 作者xujingyang. E-mail:xjy06@foxmail.com
13  * @version 创建时间:2018年1月17日 下午3:25:59
14  * @类说明:
15  */
16 public class QuartzJob implements Job {
17     /* 日志记录对象 */
18     private static  Logger logger = Logger.getLogger(QuartzJob.class);
19     
20     @Override
21     public void execute(JobExecutionContext arg0) throws JobExecutionException {
22          System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "★★★★★★★★★★★开始下载");
23          try {
24             CSVDownload.csvDownloadByUrl();
25         } catch (Exception e) {
26             e.printStackTrace();
27         }
28     }
29 }

 

同时用到了,系统启动监听类:

1.首先定义接口继承EventListener 

 1 package com.datcent.systemStartup.startupListener;
 2 
 3 import java.util.EventListener ;
 4 import org.springframework.context.ApplicationEvent ;
 5 
 6 /**
 7  * @author 作者xujingyang. E-mail:xjy06@foxmail.com
 8  * @version 创建时间:2018年1月17日 下午4:15:59
 9  * @类说明: ApplicationListener<ApplicationEvent> 接口
10  */
11 public interface StartupListener<E extends ApplicationEvent> extends EventListener {
12     void onApplicationEvent(E var1);
13 }

 2.实现接口,接口中实现的放对任务调度进行管理

 1 package com.datcent.systemStartup.startupListenerImpl;
 2 
 3 import com.datcent.core.comm.GLOBAL_CONSTANT;
 4 import com.datcent.core.util.PropertiesLoader;
 5 import com.datcent.downloadCSV.quartzJob.QuartzJob;
 6 import com.datcent.downloadCSV.quartzManager.QuartzManager;
 7 import com.datcent.systemStartup.startupListener.StartupListener;
 8 import org.quartz.Scheduler;
 9 import org.quartz.SchedulerFactory;
10 import org.quartz.impl.StdSchedulerFactory;
11 import org.springframework.beans.BeansException;
12 import org.springframework.beans.factory.InitializingBean;
13 import org.springframework.context.ApplicationContext;
14 import org.springframework.context.ApplicationContextAware;
15 import org.springframework.context.event.ContextRefreshedEvent;
16 import org.springframework.stereotype.Component;
17 import org.springframework.web.context.ServletContextAware;
18 
19 import javax.servlet.ServletContext;
20 
21 /**
22  * @author 作者xujingyang. E-mail:xjy06@foxmail.com
23  * @version 创建时间:2018年1月17日 下午4:17:16
24  * @类说明: 程序启动执行,方法从上到下执行顺序:1->2->3->4 其中4会执行多次
25  */
26 @Component
27 public class StartupListenerImpl implements StartupListener<ContextRefreshedEvent>, ApplicationContextAware,
28         ServletContextAware, InitializingBean {
29 
30     /*
31      * 1
32      */
33     @Override
34     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
35         try {
36             // 获取配置文件时间
37             PropertiesLoader loader = new PropertiesLoader(GLOBAL_CONSTANT.CSV_DOWLOAD_TIME_FILEPATH);
38             String csvDownloadTime = loader.getProperty(GLOBAL_CONSTANT.CSV_DOWLOAD_TIME_KEY);
39             String cronTime = "0 0/"+csvDownloadTime+" * * * ? ";
40 
41             System.out.println(cronTime);
42 
43             // 启动定时任务
44             SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
45             Scheduler sche = gSchedulerFactory.getScheduler();
46             System.out.println("【系统启动】开始...");
47             QuartzManager.addJob(sche, GLOBAL_CONSTANT.JOB_NAME, QuartzJob.class, cronTime);
48         } catch (Exception e) {
49             e.printStackTrace();
50         }
51     }
52 
53     /*
54      * 2
55      */
56     @Override
57     public void setServletContext(ServletContext arg0) {
58     }
59 
60     /*
61      * 3:初始化bean之前
62      */
63     @Override
64     public void afterPropertiesSet() throws Exception {
65 
66     }
67 
68     /*
69      * 4,bean被注入时执行
70      */
71     @Override
72     public void onApplicationEvent(ContextRefreshedEvent evt) {
73     }
74 
75 }

 

 

任务调度动态管理,大致就是这么简单。

 

posted @ 2018-03-16 14:23  oldmonk  阅读(1633)  评论(0编辑  收藏  举报
Fork me on GitHub