zhibing.pu
2024-07-25 79fc712ed025069c1d21de230bdc95c74910288c
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package com.stylefeng.guns.modular.system.util.quartz;
 
import com.stylefeng.guns.modular.system.util.quartz.model.QuartzEnum;
import com.stylefeng.guns.modular.system.util.quartz.model.QuartzJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
 
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
 
/**
 * quartz任务调度工具类
 * @author zhibing.pu
 * @Date 2024/3/20 11:12
 */
@Slf4j
public class QuartzUtil {
    /**
     * 构建调度器
     */
    public static Scheduler scheduler;
    
    
    /**
     * 启动调度器
     * @param propertiesStream 配置文件流
     * @return
     */
    public static void start(InputStream propertiesStream){
        if(null == scheduler){
            scheduler = SchedulerUtil.getScheduler(propertiesStream);
        }
        try {
            scheduler.start();
            log.info(QuartzEnum.SCHEDULER_START_SUCCESS.getValue());
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
    
    
    
    
    
    /**
     * 添加普通定时任务
     * @param quartzJob 任务类
     * @param startTime 任务开始执行时间,为空则立即执行
     * @param intervalInMilliseconds 执行间隔毫秒数
     * @param repeatCount 重复执行次数,-1表示永远执行
     * @throws SchedulerException
     */
    public static void addSimpleQuartzTask(QuartzJob quartzJob, Date startTime, long intervalInMilliseconds, int repeatCount) throws SchedulerException {
        if(null == scheduler){
            log.error("请先加载任务调取器");
            return;
        }
        JobDetail jobDetail = getJobDetail(quartzJob);
        Trigger simpleTrigger = getSimpleTrigger(quartzJob, startTime, intervalInMilliseconds, repeatCount);
        scheduler.scheduleJob(jobDetail, simpleTrigger);
        log.info(QuartzEnum.ADD_SIMPLE_TRIGGER_SUCCESS.getValue());
    }
    
    
    
    /**
     * 添加Cron表达式的定时任务
     * @param quartzJob 任务类
     * @param cron cron表达式
     * @throws SchedulerException
     */
    public static void addCronQuartzTask(QuartzJob quartzJob, String cron) throws SchedulerException {
        if(null == scheduler){
            log.error("请先加载任务调取器");
            return;
        }
        JobDetail jobDetail = getJobDetail(quartzJob);
        Trigger cronTrigger = getCronTrigger(quartzJob, cron);
        scheduler.scheduleJob(jobDetail, cronTrigger);
        log.info(QuartzEnum.ADD_CRON_TRIGGER_SUCCESS.getValue());
    }
    
    
    /**
     * 删除任务
     * @param name 任务名称
     * @param group 任务分组
     * @return
     */
    public static boolean deleteQuartzTask(String name, String group){
        JobKey jobKey = new JobKey(name, group);
        boolean b = false;
        try {
            b = scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
        return b;
    }
    
    /**
     * 删除任务
     * @param jobKey
     * @return
     */
    public static boolean deleteQuartzTask(JobKey jobKey){
        boolean b = false;
        try {
            b = scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
        return b;
    }
    
    /**
     * 删除分组下的所有定时任务
     * @param group 分组名称
     * @return
     */
    public static boolean deleteGroupQuartzTask(String group){
        try {
            GroupMatcher<JobKey> groupMatcher = GroupMatcher.groupEquals(group);
            Set<JobKey> jobKeys = scheduler.getJobKeys(groupMatcher);
            boolean b = scheduler.deleteJobs(jobKeys.stream().collect(Collectors.toList()));
            if(!b){
                return false;
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
    
    
    
    /**
     * 清空所有定时任务
     * @return
     */
    public static boolean deleteAllQuartzTask(){
        try {
            List<String> jobGroupNames = scheduler.getJobGroupNames();
            for (String jobGroupName : jobGroupNames) {
                GroupMatcher<JobKey> groupMatcher = GroupMatcher.groupEquals(jobGroupName);
                Set<JobKey> jobKeys = scheduler.getJobKeys(groupMatcher);
                boolean b = scheduler.deleteJobs(jobKeys.stream().collect(Collectors.toList()));
                if(!b){
                    return false;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
    
    
    
    
    
    /**
     * 构建任务描述JobDetail对象
     * @param quartzJob 任务对象
     * @return
     */
    private static JobDetail getJobDetail(QuartzJob quartzJob){
        String name = quartzJob.getName();
        String group = quartzJob.getGroup();
        if(null == name || "".equals(name)){
            name = QuartzEnum.JOB_NAME.getValue();
        }
        if(null == group || "".equals(group)){
            group = QuartzEnum.DEFAULT_GROUP.getValue();
        }
        return getJobDetail(quartzJob, name, group, quartzJob.getJobDataMap());
    }
    
    
    
    /**
     * 构建任务描述JobDetail对象
     * @param job 任务类
     * @param job_name 任务名称
     * @param group_name 任务分组名称
     * @param jobDataMap 自定义参数
     * @return
     */
    private static JobDetail getJobDetail(Job job, String job_name, String group_name, JobDataMap jobDataMap){
        JobDetail jobDetail = JobBuilder.newJob(job.getClass())
                .withIdentity(job_name, group_name)
                .setJobData(jobDataMap)
                .build();
        return jobDetail;
    }
    
    
    /**
     * 构建Trigger执行器
     * @param quartzJob 任务类
     * @param startTime 任务开始执行时间,为空则立即执行
     * @param intervalInMilliseconds 执行间隔毫秒数
     * @param repeatCount 重读执行次数,-1表示永远执行
     * @return
     */
    private static Trigger getSimpleTrigger(QuartzJob quartzJob, Date startTime, long intervalInMilliseconds, int repeatCount){
        String name = quartzJob.getName();
        String group = quartzJob.getGroup();
        if(null == name || "".equals(name)){
            name = QuartzEnum.JOB_NAME.getValue();
        }
        if(null == group || "".equals(group)){
            group = QuartzEnum.DEFAULT_GROUP.getValue();
        }
        TriggerBuilder<Trigger> triggerTriggerBuilder = TriggerBuilder.newTrigger();
        if(null == startTime){
            triggerTriggerBuilder.startNow();
        }else{
            triggerTriggerBuilder.startAt(startTime);
        }
        
        SimpleTrigger trigger = triggerTriggerBuilder
                .withIdentity(name, group)
                .withSchedule(
                        SimpleScheduleBuilder
                                .simpleSchedule()
                                .withIntervalInMilliseconds(intervalInMilliseconds)
                                .withRepeatCount(repeatCount)
                ).build();
        return trigger;
    }
    
    
    /**
     * 构建cronExpression表达式执行器
     * @param quartzJob 任务类
     * @param cron cron表达式
     * @return
     */
    private static Trigger getCronTrigger(QuartzJob quartzJob, String cron) {
        String name = quartzJob.getName();
        String group = quartzJob.getGroup();
        if(null == name || "".equals(name)){
            name = QuartzEnum.JOB_NAME.getValue();
        }
        if(null == group || "".equals(group)){
            group = QuartzEnum.DEFAULT_GROUP.getValue();
        }
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .startNow()
                .withIdentity(name, group)
                .withSchedule(
                        CronScheduleBuilder.cronSchedule(cron)
                ).build();
        return trigger;
    }
    
    
}