Springboot集成ScheduleTask
# 流程图
# Yml
#定时任务是否开启及组名
jobSelf:
enable: true
jobGroupName: group1
1
2
3
4
2
3
4
# pom
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version><!--$NO-MVN-MAN-VER$ -->
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# Java
# 工具类
# ScheduleTask
package cn.ok96;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* 定时工具类
*
* @author Nepk
*/
@Slf4j
@Component
public class ScheduleTask {
private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
@Resource
private JobInfoRepository jobInfoRepository;
@Resource
private JobTypeRepository jobTypeRepository;
@Value("${jobSelf.jobGroupName}")
private String jobGroupName;
@Value("${jobSelf.enable}")
private Boolean enable;
/**
* 启动工程时加载job
* @throws SchedulerException
*/
@SuppressWarnings("unchecked")
public void scheduleJobs() {
if (enable){
log.info("启动工程时加载job");
List<JobInfo> jobInfos = JobInfoRepository.findAll();
if (jobInfos.isEmpty()) {
log.info("没有可执行的任务");
return;
} else {
for (WfitJobInfo jobInfo : jobInfos) {
Map<String, Object> map = new HashMap<>();
map.put("jobId", jobInfo.getId());
WfitJobType jobType = jobTypeRepository.getById(jobInfo.getJobTypeId());
if (jobInfo!=null){
setJob(jobInfo.getJobCron(), jobGroupName, jobInfo.getId()+""
,jobType.getJobPath() , map, jobInfo.getJobStatus() == 2);
}
}
}
}
}
/**
* 设置定时
*
* @param time
* @param group ----这个是组
* @param jobId ----这个是name
* @param job ----cn.ok96.job.xxx
* @param params ----参数
*/
public void setJob(String time, String group, String jobId, String job, Map<String, Object> params, Boolean
isPauseJob) {
try {
Scheduler scheduler = gSchedulerFactory.getScheduler();
Class jobClass = Class.forName(job);
// 设置Job的名字和组
JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobId, group).build();
//动态添加数据 放置参数
if (params.size() > 0) {
for (Entry<String, Object> entry : params.entrySet()) {
jobDetail.getJobDataMap().put(entry.getKey(), entry.getValue());
}
}
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(time);
//设置定时任务的时间触发规则
CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(jobId, group).withSchedule(scheduleBuilder).build();
// 把作业和触发器注册到任务调度中
scheduler.scheduleJob(jobDetail, cronTrigger);
if (isPauseJob) {
JobKey jobKey = new JobKey(jobId, group);
scheduler.pauseJob(jobKey);
} else {
scheduler.start();
}
} catch (Exception e) {
log.error("创建任务失败", e);
throw new RuntimeException(e);
}
}
/***
* 修改定时任务时间
* @param triggerName
* @param triggerGroupName
* @param time
*/
public Boolean modifyJobTime(String triggerName, String triggerGroupName, String time) {
try {
Scheduler scheduler = gSchedulerFactory.getScheduler();
TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroupName);
CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
if (trigger == null) {
return false;
}
System.out.println(scheduler.getTriggerState(triggerKey));
String oldTime = trigger.getCronExpression();
// Trigger已存在,那么更新相应的定时设置
if (!oldTime.equalsIgnoreCase(time)) {
//设置一个新的定时时间
CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(time);
// 按新的cronExpression表达式重新构建trigger
CronTrigger cronTrigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
// 按新的trigger重新设置job执行
scheduler.rescheduleJob(triggerKey, cronTrigger);
}
return true;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/****
* 暂停一个任务
* @param triggerName
* @param triggerGroupName
*/
public Boolean pauseJob(String triggerName, String triggerGroupName) {
try {
Scheduler scheduler = gSchedulerFactory.getScheduler();
JobKey jobKey = new JobKey(triggerName, triggerGroupName);
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
if (jobDetail == null) {
return false;
}
scheduler.pauseJob(jobKey);
return true;
} catch (SchedulerException e) {
log.error("暂停任务失败", e);
throw new RuntimeException(e);
}
}
/****
* 删除一个任务
* @param triggerName
* @param triggerGroupName
*/
public Boolean deleteJob(String triggerName, String triggerGroupName) {
try {
Scheduler scheduler = gSchedulerFactory.getScheduler();
JobKey jobKey = new JobKey(triggerName, triggerGroupName);
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
if (jobDetail == null) {
return false;
}
scheduler.deleteJob(jobKey);
return true;
} catch (SchedulerException e) {
log.error("删除任务失败", e);
throw new RuntimeException(e);
}
}
/****
* 恢复一个任务
* @param triggerName
* @param triggerGroupName
*/
public Boolean resumeJob(String triggerName, String triggerGroupName) {
try {
Scheduler scheduler = gSchedulerFactory.getScheduler();
JobKey jobKey = new JobKey(triggerName, triggerGroupName);
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
if (jobDetail == null) {
return false;
}
scheduler.resumeJob(jobKey);
return true;
} catch (SchedulerException e) {
log.error("恢复任务失败", e);
throw new RuntimeException(e);
}
}
/***
* 立即执行定时任务
*/
public Boolean doJob(String triggerName, String triggerGroupName) {
try {
Scheduler scheduler = gSchedulerFactory.getScheduler();
JobKey jobKey = JobKey.jobKey(triggerName, triggerGroupName);
JobDetail jobDetail = scheduler.getJobDetail(jobKey);
if (jobDetail == null) {
return false;
}
TriggerKey key = new TriggerKey(triggerName, triggerGroupName);
int ordinal = scheduler.getTriggerState(key).ordinal();
if (ordinal == 2) {
scheduler.triggerJob(jobKey);
scheduler.resumeJob(jobKey);
} else {
scheduler.triggerJob(jobKey);
}
return true;
} catch (SchedulerException e) {
log.error("立即执行任务失败", e);
throw new RuntimeException(e);
}
}
/***
* 判断任务是否存在
*/
public Boolean findJob(String triggerName, String triggerGroupName) {
try {
Scheduler scheduler = gSchedulerFactory.getScheduler();
JobKey jobKey = JobKey.jobKey(triggerName, triggerGroupName);
return scheduler.checkExists(jobKey);
} catch (SchedulerException e) {
e.printStackTrace();
}
return false;
}
}
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
239
240
241
242
243
244
245
246
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
239
240
241
242
243
244
245
246
# SpringApplicationContextUse
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringApplicationContextUse implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringApplicationContextUse.applicationContext == null) {
SpringApplicationContextUse.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);
}
}
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
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
# 启动监听类
# AppStartFinishedListener
package cn.ok96;
import cn.ok96.ScheduleTask;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class AppStartFinishedListener implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
ScheduleTask scheduleTask = (ScheduleTask) SpringApplicationContextUse.getBean("scheduleTask");
scheduleTask.scheduleJobs();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 定时任务Job
TempJob
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class TempJob implements Job {
public JobInfoRepository jobInfoRepository = SpringApplicationContextUse.getBean(JobInfoRepository.class);
public JobMessageRepository jobMessageRepository = SpringApplicationContextUse.getBean(JobMessageRepository.class);
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
Long jobId = jobDataMap.getLong("jobId");
WfitJobInfo wfitJobInfo = wfitJobInfoRepository.getById(jobId);
JSONObject jobPara =JSONObject.parseObject(wfitJobInfo.getJobPara());
Long jobTypeId = wfitJobInfo.getJobTypeId();
//String paraTemp = jobPara.getString("paraTemp");定时任务参数
WfitJobMessage message =new WfitJobMessage();
message.setJobId(jobId);
message.setCreateTime(LocalDateTime.now());
message.setDeleteFlag(false);
message.setJobTypeId(jobTypeId);
message.setId(1l);
message.setMessageStatus(1);
message.setMessageBrief("插入成功");
message.setMessageInfo("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
jobMessageRepository.save(message);
}
}
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
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
# Mysql
# 任务类型
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for job_type
-- ----------------------------
DROP TABLE IF EXISTS `job_type`;
CREATE TABLE `job_type` (
`id` bigint(20) NOT NULL,
`job_path` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'job工程路径',
`job_type_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'job类型名称',
`job_para_temp` mediumtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT 'job所需参数模板',
`modify_time` datetime NULL DEFAULT NULL COMMENT '更新时间',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
`delete_flag` tinyint(1) NULL DEFAULT NULL COMMENT '数字标识位',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '定时任务类型' ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 定时任务
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for job_info
-- ----------------------------
DROP TABLE IF EXISTS `job_info`;
CREATE TABLE `job_info` (
`id` bigint(20) NOT NULL,
`job_cron` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'corn表达式',
`job_type_id` bigint(20) NULL DEFAULT NULL COMMENT 'job类型表id',
`job_para` mediumtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT 'job所需参数',
`job_status` int(2) NULL DEFAULT NULL COMMENT '1启动2暂停,默认1',
`job_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '任务名称',
`modify_time` datetime NULL DEFAULT NULL COMMENT '更新时间',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
`delete_flag` tinyint(1) NULL DEFAULT NULL COMMENT '数字标识位',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '定时任务表' ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 执行日志
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for job_message
-- ----------------------------
DROP TABLE IF EXISTS `job_message`;
CREATE TABLE `job_message` (
`id` bigint(20) NOT NULL,
`job_id` bigint(20) NULL DEFAULT NULL COMMENT '定时任务id',
`job_type_id` bigint(20) NULL DEFAULT NULL COMMENT 'job类型表id',
`message_status` int(2) NULL DEFAULT NULL COMMENT '状态|1:待处理|0:已处理',
`message_info` mediumtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '信息文本',
`message_brief` mediumtext CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '信息文本概要',
`modify_time` datetime NULL DEFAULT NULL COMMENT '更新时间',
`create_time` datetime NULL DEFAULT NULL COMMENT '创建时间',
`delete_flag` tinyint(1) NULL DEFAULT NULL COMMENT '数字标识位',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '定时任务信息' ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
上次更新: 2023/06/16, 09:58:37