下面介绍SSM+Quartz的示例,项目地址: quartz-spring

一:环境介绍

1
2
3
4
5
6
工具:Spring Tool Suite + Mysql
框架:Spring+SpringMVC+Mybatis
前端: easy ui
日志:logback
构建工具:Maven
Quartz版本:2.2.3

二:SSM+Quartz集成详解

1.项目结构

结构项目

2.配置文件介绍

(1):在ApplicationContext.xml中添加下面的配置:

1
2
3
4
5
6
<bean name="quartzScheduler"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="dataSource" ref="dataSource" /><!-- 读取spring配置的数据库,不去加载quartz.properties -->
<property name="applicationContextSchedulerContextKey" value="applicationContextKey" />
<property name="configLocation" value="classpath:quartz.properties" />
</bean>

(2):添加quartz.properties配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Default Properties file for use by StdSchedulerFactory
# to create a Quartz Scheduler Instance, if a different
# properties file is not explicitly specified.
#
org.quartz.scheduler.instanceName: DefaultQuartzScheduler
#org.quartz.scheduler.instanceId = AUTO
org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 10
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true
#持久化配置
org.quartz.jobStore.misfireThreshold: 60000
org.quartz.jobStore.class: org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.useProperties:true
#指定前缀
org.quartz.jobStore.tablePrefix: QRTZ_

3.核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package com.wyj.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerKey;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.wyj.entity.JobDto;
import com.wyj.entity.Retval;
import com.wyj.service.QuartzService;
/**
* 定时任务 Controller
*
*
* @author:WangYuanJun
* @date:2018年1月7日 下午10:15:33
*/
@Controller
@RequestMapping(value = "/quartz")
public class QuartzController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private Scheduler quartzScheduler;
@Autowired
private QuartzService quartzService;
@RequestMapping("/index")
public String index() {
return "/quartz/list";
}
/**
* 定时列表页
*
* @return
* @throws SchedulerException
*/
@ResponseBody
@RequestMapping(value = "/list")
public String listJob(HttpServletRequest request, HttpServletResponse response) throws SchedulerException {
List<JobDto> jobInfos = this.getSchedulerJobInfo();
return JSON.toJSONString(jobInfos);
}
/**
* 新建job
*
* @param jobDto
* @return
*/
@ResponseBody
@RequestMapping(value = "/add")
public Retval save(JobDto jobDto) {
Retval retval = Retval.newInstance();
try {
quartzService.addJob(jobDto.getJobName(), jobDto.getJobGroupName(), jobDto.getTriggerName(), jobDto.getTriggerGroupName(), Class.forName(jobDto.getJobClass()), jobDto.getCronExpression());
} catch (Exception e) {
logger.error(e.getMessage());
}
return retval;
}
/**
* 编辑job
*
* @param jobDto
* @return
*/
@ResponseBody
@RequestMapping(value = "/edit", method = RequestMethod.POST)
public Retval edit(JobDto jobDto) {
Retval retval = Retval.newInstance();
try {
boolean result = quartzService.modifyJobTime(jobDto.getOldJobName(), jobDto.getOldJobGroupName(), jobDto.getOldTriggerName(), jobDto.getOldTriggerGroupName(), jobDto.getJobName(), jobDto.getJobGroupName(), jobDto.getTriggerName(), jobDto.getTriggerGroupName(), jobDto.getCronExpression());
if (result) {
retval.put("message", "修改任务成功!");
} else {
retval.put("message", "修改任务失败!");
}
} catch (Exception e) {
logger.error(e.getMessage());
}
return retval;
}
/**
* 暂停job
*
* @param jobName
* @param jobGroupName
* @return
*/
@ResponseBody
@RequestMapping(value = "/stopJob", method = RequestMethod.POST)
public Retval stopJob(@RequestParam("jobName") String jobName, @RequestParam("jobGroupName") String jobGroupName) {
Retval retval = Retval.newInstance();
if (StringUtils.isEmpty(jobName) || StringUtils.isEmpty(jobGroupName)) {
retval.fail();
retval.put("message", "暂停失败");
} else {
try {
quartzService.pauseJob(jobName, jobGroupName);
retval.put("message", "暂停成功");
} catch (Exception e) {
logger.error(e.getMessage());
}
}
return retval;
}
/**
* 恢复job
*
* @param jobName
* @param jobGroupName
* @return
*/
@ResponseBody
@RequestMapping(value = "/resumeJob", method = RequestMethod.POST)
public Retval resumeJob(@RequestParam("jobName") String jobName, @RequestParam("jobGroupName") String jobGroupName) {
Retval retval = Retval.newInstance();
if (StringUtils.isEmpty(jobName) || StringUtils.isEmpty(jobGroupName)) {
retval.fail();
retval.put("message", "恢复失败");
} else {
try {
quartzService.resumeJob(jobName, jobGroupName);
retval.put("message", "恢复成功");
} catch (Exception e) {
logger.error(e.getMessage());
}
}
return retval;
}
/**
* 删除job
*
* @param jobName
* @param jobGroupName
* @param triggerName
* @param triggerGroupName
* @return
*/
@RequestMapping(value = "/deleteJob", method = RequestMethod.POST)
@ResponseBody
public Retval deleteJob(@RequestParam("jobName") String jobName, @RequestParam("jobGroupName") String jobGroupName, @RequestParam("triggerName") String triggerName, @RequestParam("triggerGroupName") String triggerGroupName) {
Retval retval = Retval.newInstance();
if (StringUtils.isEmpty(jobName) || StringUtils.isEmpty(jobGroupName) || StringUtils.isEmpty(triggerName) || StringUtils.isEmpty(triggerGroupName)) {
retval.fail();
retval.put("message", "删除失败");
} else {
try {
quartzService.removeJob(jobName, jobGroupName, triggerName, triggerGroupName);
retval.put("message", "删除成功");
} catch (Exception e) {
logger.error(e.getMessage());
}
}
return retval;
}
private List<JobDto> getSchedulerJobInfo() throws SchedulerException {
List<JobDto> jobInfos = new ArrayList<JobDto>();
List<String> triggerGroupNames = quartzScheduler.getTriggerGroupNames();
for (String triggerGroupName : triggerGroupNames) {
Set<TriggerKey> triggerKeySet = quartzScheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(triggerGroupName));
for (TriggerKey triggerKey : triggerKeySet) {
Trigger t = quartzScheduler.getTrigger(triggerKey);
if (t instanceof CronTrigger) {
CronTrigger trigger = (CronTrigger) t;
JobKey jobKey = trigger.getJobKey();
JobDetail jd = quartzScheduler.getJobDetail(jobKey);
JobDto jobInfo = new JobDto();
jobInfo.setJobName(jobKey.getName());
jobInfo.setJobGroupName(jobKey.getGroup());
jobInfo.setTriggerName(triggerKey.getName());
jobInfo.setTriggerGroupName(triggerKey.getGroup());
jobInfo.setCronExpression(trigger.getCronExpression());
jobInfo.setNextFireTime(trigger.getNextFireTime());
jobInfo.setPreviousFireTime(trigger.getPreviousFireTime());
jobInfo.setStartTime(trigger.getStartTime());
jobInfo.setEndTime(trigger.getEndTime());
jobInfo.setJobClass(jd.getJobClass().getCanonicalName());
// jobInfo.setDuration(Long.parseLong(jd.getDescription()));
Trigger.TriggerState triggerState = quartzScheduler.getTriggerState(trigger.getKey());
jobInfo.setJobStatus(triggerState.toString());// NONE无,
// NORMAL正常,
// PAUSED暂停,
// COMPLETE完全,
// ERROR错误,
// BLOCKED阻塞
JobDataMap map = quartzScheduler.getJobDetail(jobKey).getJobDataMap();
if (null != map && map.size() != 0) {
jobInfo.setCount(Long.valueOf((String) map.get("count")));
jobInfo.setJobDataMap(map);
} else {
jobInfo.setJobDataMap(new JobDataMap());
}
jobInfos.add(jobInfo);
}
}
}
return jobInfos;
}
}

4.job

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.wyj.job;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
* Job任务
*
*
* @author:WangYuanJun
* @date:2018年1月5日 下午10:22:42
*/
public class HelloWorldJob implements Job {
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println("----hello world---" + new Date());
}
}

三:运行效果介绍

编辑页面
控制台