Spring4+Springmvc+quartz实现多线程动态定时调度

scheduler定时调度系统是大多行业项目都需要的,传统的spring-job模式,个人感觉已经out了,因为存在很多的问题,特别是定时调度的追加、修改、删除等,需要修改xml,xml的配置生效无非是热部署灰度发布方案或者直接停止、重启服务器,完全不能做到自动启动、修复方式。(企业架构源码可以加求球:叁五三陆二肆柒二伍玖)

提醒:可以对应用进行集群部署,在对定时调度配置时可以使用集群方式或者单边配置应用方式,今天讲解的是使用spring4+scheduler实现定时调度,闲话少说,直接把步骤记录下来:

  1. 在项目的pom.xml文件中引入quartz的jar包,如下:
1.   <!-- quartz定时调度 --> 
2.  lt;dependency> 
3.  <groupId>org.quartz-scheduler</groupId> 
4.  <artifactId>quartz</artifactId> 
5.  <version>1.8.5</version> 
6.  lt;/dependency>
  1. 定义quartz的配置文件spring-context-quartz.xml:
1.  <?xml version="1.0" encoding="UTF-8"?> 
2.  <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
3.   xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" 
4.   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
5.   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd" 
6.   default-lazy-init="false"> 
7.   <!-- 调度器 --> 
8.   <bean name="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> 
9.   <!-- 通过applicationContextSchedulerContextKey属性配置spring上下文 --> 
10.   <property name="applicationContextSchedulerContextKey" value="applicationContext" /> 
11.   </bean> 
12.   <!--加载数据库任务--> 
13.   <bean id="jobService" class="com.ml.honghu.job.service.JobService" init-method="loadJob" /> 
14.  </beans>
  1. 在项目的web.xml文件中引入spring-context-quartz.xml配置文件
1.  classpath*:spring-context-quartz.xml
  1. 定义job实体对象
1.  public class Job{ 

3.   private static final long serialVersionUID = 1L; 

5.   /** 
6.   * 任务执行周期cron表达式 
7.   */ 
8.   public static int EXECYCLE_CRON = 2; 
9.   /** 
10.   * 任务执行周期自定义 
11.   */ 
12.   public static int EXECYCLE_DEFINE = 1; 
13.   /** 
14.   * 执行周期-分钟 
15.   */ 
16.   public static int EXECYCLE_MINUTE = 1; 
17.   /** 
18.   * 执行周期-小时 
19.   */ 
20.   public static int EXECYCLE_HOUR = 2; 
21.   /** 
22.   * 执行周期-日 
23.   */ 
24.   public static int EXECYCLE_DAY = 3; 
25.   /** 
26.   * 执行周期-月 
27.   */ 
28.   public static int EXECYCLE_WEEK = 4; 
29.   /** 
30.   * 执行周期-月 
31.   */ 
32.   public static int EXECYCLE_MONTH = 5; 

35.   private String jobType; // 任务类型(1首页静态化、2栏目页静态化、3内容页静态化、4采集、5分发) 
36.   private String jobName; // 任务名称 
37.   private String jobClass; // 任务类 
38.   private String execycle; // 执行周期分类(1非表达式 2 cron表达式) 
39.   private String dayOfMonth; // 每月的哪天 
40.   private String dayOfWeek; // 周几 
41.   private String hour; // 小时 
42.   private String minute; // 分钟 
43.   private String intervalHour; // 间隔小时 
44.   private String intervalMinute; // 间隔分钟 
45.   private String jobIntervalUnit; // 1分钟、2小时、3日、4周、5月 
46.   private String cronExpression; // 规则表达式 
47.   private String isEnable; // 是否启用 

49.   public Job() { 
50.   super(); 
51.   } 

53.   public Job(String id){ 
54.   super(id); 
55.   } 

57.   @Length(min=1, max=1, message="任务类型(1首页静态化、2栏目页静态化、3内容页静态化、4采集、5分发)长度必须介于 1 和 1 之间") 
58.   public String getJobType() { 
59.   return jobType; 
60.   } 

62.   public void setJobType(String jobType) { 
63.   this.jobType = jobType; 
64.   } 

66.   @Length(min=1, max=255, message="任务名称长度必须介于 1 和 255 之间") 
67.   public String getJobName() { 
68.   return jobName; 
69.   } 

71.   public void setJobName(String jobName) { 
72.   this.jobName = jobName; 
73.   } 

75.   @Length(min=1, max=255, message="任务类长度必须介于 1 和 255 之间") 
76.   public String getJobClass() { 
77.   return jobClass; 
78.   } 

80.   public void setJobClass(String jobClass) { 
81.   this.jobClass = jobClass; 
82.   } 

84.   @Length(min=1, max=1, message="执行周期分类(1非表达式 2 cron表达式)长度必须介于 1 和 1 之间") 
85.   public String getExecycle() { 
86.   return execycle; 
87.   } 

89.   public void setExecycle(String execycle) { 
90.   this.execycle = execycle; 
91.   } 

93.   @Length(min=0, max=11, message="每月的哪天长度必须介于 0 和 11 之间") 
94.   public String getDayOfMonth() { 
95.   return dayOfMonth; 
96.   } 

98.   public void setDayOfMonth(String dayOfMonth) { 
99.   this.dayOfMonth = dayOfMonth; 
100.   } 

102.   @Length(min=0, max=1, message="周几长度必须介于 0 和 1 之间") 
103.   public String getDayOfWeek() { 
104.   return dayOfWeek; 
105.   } 

107.   public void setDayOfWeek(String dayOfWeek) { 
108.   this.dayOfWeek = dayOfWeek; 
109.   } 

111.   @Length(min=0, max=11, message="小时长度必须介于 0 和 11 之间") 
112.   public String getHour() { 
113.   return hour; 
114.   } 

116.   public void setHour(String hour) { 
117.   this.hour = hour; 
118.   } 

120.   @Length(min=0, max=11, message="分钟长度必须介于 0 和 11 之间") 
121.   public String getMinute() { 
122.   return minute; 
123.   } 

125.   public void setMinute(String minute) { 
126.   this.minute = minute; 
127.   } 

129.   @Length(min=0, max=11, message="间隔小时长度必须介于 0 和 11 之间") 
130.   public String getIntervalHour() { 
131.   return intervalHour; 
132.   } 

134.   public void setIntervalHour(String intervalHour) { 
135.   this.intervalHour = intervalHour; 
136.   } 

138.   @Length(min=0, max=11, message="间隔分钟长度必须介于 0 和 11 之间") 
139.   public String getIntervalMinute() { 
140.   return intervalMinute; 
141.   } 

143.   public void setIntervalMinute(String intervalMinute) { 
144.   this.intervalMinute = intervalMinute; 
145.   } 

147.   @Length(min=0, max=1, message="1分钟、2小时、3日、4周、5月长度必须介于 0 和 1 之间") 
148.   public String getJobIntervalUnit() { 
149.   return jobIntervalUnit; 
150.   } 

152.   public void setJobIntervalUnit(String jobIntervalUnit) { 
153.   this.jobIntervalUnit = jobIntervalUnit; 
154.   } 

156.   @Length(min=0, max=255, message="规则表达式长度必须介于 0 和 255 之间") 
157.   public String getCronExpression() { 
158.   return cronExpression; 
159.   } 

161.   public void setCronExpression(String cronExpression) { 
162.   this.cronExpression = cronExpression; 
163.   } 

165.   @Length(min=1, max=1, message="是否启用长度必须介于 1 和 1 之间") 
166.   public String getIsEnable() { 
167.   return isEnable; 
168.   } 

170.   public void setIsEnable(String isEnable) { 
171.   this.isEnable = isEnable; 
172.   } 

174.  }
  1. 编写quartz的jobServvice类:
1.  package com.ml.honghu.job.service; 

3.  import java.text.ParseException; 
4.  import java.util.List; 
5.  import java.util.UUID; 

7.  import org.quartz.CronTrigger; 
8.  import org.quartz.JobDetail; 
9.  import org.quartz.Scheduler; 
10.  import org.quartz.SchedulerException; 
11.  import org.slf4j.Logger; 
12.  import org.slf4j.LoggerFactory; 
13.  import org.springframework.beans.factory.annotation.Autowired; 
14.  import org.springframework.stereotype.Service; 
15.  import org.springframework.transaction.annotation.Transactional; 

17.  import com.ml.honghu.StringUtils; 
18.  import com.ml.honghu.common.persistence.Page; 
19.  import com.ml.honghu.common.service.CrudService; 
20.  import com.ml.honghu.job.dao.JobDao; 
21.  import com.ml.honghu.job.entity.Job; 

23.  /** 
24.   * 定时调度任务Service 
25.   * 
26.   * @author honghu 
27.   */ 
28.  @Service 
29.  @Transactional(readOnly = true) 
30.  public class JobService extends CrudService<JobDao, Job> { 

32.   @Autowired 
33.   private JobDao jobDao; 

35.   private Logger logger = LoggerFactory.getLogger(getClass()); 

37.   public Job get(String id) { 
38.   return super.get(id); 
39.   } 

41.   public List<Job> findList(Job job) { 
42.   return super.findList(job); 
43.   } 

45.   public Page<Job> findPage(Page<Job> page, Job job) { 
46.   return super.findPage(page, job); 
47.   } 

49.   @Transactional(readOnly = false) 
50.   public void save(Job job) { 
51.   super.save(job); 
52.   // 启用则启动任务 
53.   if (StringUtils.equals("1", job.getIsEnable())) { 
54.   startTask(job, job.getId()); 
55.   } 
56.   } 

58.   @Transactional(readOnly = false) 
59.   public void update(Job job) { 
60.   //结束定时调度 
61.   endTask(job.getId()); 

63.   job.preUpdate(); 
64.   jobDao.update(job); 

66.   // 启用则启动任务 
67.   if (StringUtils.equals("1", job.getIsEnable())) { 
68.   startTask(job, job.getId()); 
69.   } 
70.   } 

72.   @Transactional(readOnly = false) 
73.   public void delete(Job job) { 
74.   //结束任务 
75.   endTask(job.getId()); 

77.   super.delete(job); 
78.   } 

80.   /** 
81.   * 系统初始加载任务 
82.   */ 
83.   public void loadJob() throws Exception { 
84.   List<Job> jobList = this.findList(new Job()); 
85.   if (null != jobList && jobList.size() > 0) { 
86.   for (int i = 0; i < jobList.size(); i++) { 
87.   Job job = jobList.get(i); 
88.   // 任务开启状态 执行任务调度 
89.   if (StringUtils.equals("1", job.getIsEnable())) { 
90.   try { 
91.   JobDetail jobDetail = new JobDetail(); 
92.   // 设置任务名称 
93.   if (StringUtils.isNotBlank(job.getId())) { 
94.   jobDetail.setName(job.getId()); 
95.   } else { 
96.   UUID uuid = UUID.randomUUID(); 
97.   jobDetail.setName(uuid.toString()); 
98.   job.setId(uuid.toString()); 
99.   } 
100.   jobDetail.setGroup(Scheduler.DEFAULT_GROUP); 
101.   // 设置任务执行类 
102.   jobDetail.setJobClass(getClassByTask(job.getJobClass())); 
103.   // 添加任务参数 
104.   CronTrigger cronTrigger = new CronTrigger("cron_" + i, Scheduler.DEFAULT_GROUP, 
105.   jobDetail.getName(), Scheduler.DEFAULT_GROUP); 

107.   cronTrigger.setCronExpression(getCronExpressionFromDB(job.getId())); 
108.   // 调度任务 
109.   scheduler.scheduleJob(jobDetail, cronTrigger); 
110.   } catch (SchedulerException e) { 
111.   logger.error("JobService SchedulerException", e); 
112.   } catch (ClassNotFoundException e) { 
113.   logger.error("JobService ClassNotFoundException", e); 
114.   } catch (Exception e) { 
115.   logger.error("JobService Exception", e); 
116.   } 
117.   } 
118.   } 
119.   } 
120.   } 

122.   /** 
123.   * 
124.   * @param taskClassName 
125.   *            任务执行类名 
126.   * @return 
127.   * @throws ClassNotFoundException 
128.   */ 
129.   @SuppressWarnings("rawtypes") 
130.   private Class getClassByTask(String taskClassName) throws ClassNotFoundException { 
131.   return Class.forName(taskClassName); 
132.   } 

134.   public String getCronExpressionFromDB(String id) throws Exception { 
135.   // 设置任务规则 
136.   Job job = this.get(id); 
137.   if (null != job) { 
138.   if (Job.EXECYCLE_CRON == Integer.parseInt(job.getExecycle())) { 
139.   return job.getCronExpression(); 
140.   } else { 
141.   Integer execycle = Integer.parseInt(job.getJobIntervalUnit()); 
142.   String excep = ""; 
143.   if (execycle.equals(Job.EXECYCLE_MONTH)) { 
144.   excep = "0  " + job.getMinute() + " " + job.getHour() + " " + job.getDayOfMonth() + " * ?"; 
145.   } else if (execycle.equals(Job.EXECYCLE_WEEK)) { 
146.   excep = "0  " + job.getMinute() + " " + job.getHour() + " " + " ? " + " * " + job.getDayOfWeek(); 
147.   } else if (execycle.equals(Job.EXECYCLE_DAY)) { 
148.   excep = "0  " + job.getMinute() + " " + job.getHour() + " " + " * * ?"; 
149.   } else if (execycle.equals(Job.EXECYCLE_HOUR)) { 
150.   excep = "0 0 */" + job.getIntervalHour() + " * * ?"; 
151.   } else if (execycle.equals(Job.EXECYCLE_MINUTE)) { 
152.   excep = "0  */" + job.getIntervalMinute() + " * * * ?"; 
153.   } 
154.   return excep; 
155.   } 
156.   } 
157.   return ""; 
158.   } 

160.   private void startTask(Job job, String id) { 
161.   try { 
162.   String cronExpress = getCronExpressionFromDB(id); 
163.   if (StringUtils.isNotEmpty(cronExpress) && cronExpress.indexOf("null") == -1) { 
164.   JobDetail jobDetail = new JobDetail(); 
165.   jobDetail.setName(id); 
166.   jobDetail.setGroup(Scheduler.DEFAULT_GROUP); 
167.   jobDetail.setJobClass(getClassByTask(job.getJobClass())); 
168.   CronTrigger cronTrigger = new CronTrigger("cron_" + id, Scheduler.DEFAULT_GROUP, jobDetail.getName(), 
169.   Scheduler.DEFAULT_GROUP); 
170.   cronTrigger.setCronExpression(cronExpress); 
171.   scheduler.scheduleJob(jobDetail, cronTrigger); 
172.   } 
173.   } catch (ParseException e) { 
174.   logger.error("JobService ParseException", e); 
175.   } catch (Exception e) { 
176.   logger.error("JobService Exception", e); 
177.   } 
178.   } 

180.   private void endTask(String id) { 
181.   try { 
182.   scheduler.deleteJob(id, Scheduler.DEFAULT_GROUP); 
183.   } catch (SchedulerException e) { 
184.   logger.error("JobService endTask", e); 
185.   } 
186.   } 

188.   @Autowired 
189.   private Scheduler scheduler; 

191.  }
  1. 编写相关job的Controller、dao、dao.xml我这边就不写了,其实就是对数据的增删改查操作
  2. 启动项目验证quartz是否成功:

    项目启动个控制台:

image.png

  任务列表:
image.png

      任务添加和修改界面:
image.png

 到此完毕!

评论

暂无评论