Spring整合Quartz实现动态定时器的示例代码

时间:2022-05-06 05:31:06

一、版本说明

spring3.1以下的版本必须使用quartz1.x系列,3.1以上的版本才支持quartz 2.x,不然会出错。

原因:spring对于quartz的支持实现,org.springframework.scheduling.quartz.CronTriggerBean继承了org.quartz.CronTrigger,在quartz1.x系列中org.quartz.CronTrigger是个类,而在quartz2.x系列中org.quartz.CronTrigger变成了接口,从而造成无法用spring的方式配置quartz的触发器(trigger)

此示例所选版本:spring版本号3.0.7.RELEASE,quartz版本1.8.6

二、添加jar包

我的是maven工程,pom.xml相关配置如下:

?
1
2
3
4
5
<properties>
   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   <spring.version>3.0.7.RELEASE</spring.version>
   <quartz.version>1.8.6</quartz.version>
 </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
26
27
28
29
30
31
32
33
34
35
36
37
38
 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>${spring.version}</version>
  <exclusions>
    <!-- Exclude Commons Logging in favor of SLF4j -->
    <exclusion>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
    </exclusion>
  </exclusions>
</dependency>
 
<dependency><!--3.0.7没这个包 -->
  <groupId>org.springframework</groupId>
  <artifactId>spring-context-support</artifactId>
  <version>${spring.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>${spring.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-orm</artifactId>
  <version>${spring.version}</version>
  <type>jar</type>
  <scope>compile</scope>
</dependency>
 
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-test</artifactId>
  <version>${spring.version}</version>
  <type>jar</type>
  <scope>test</scope>
</dependency>
?
1
2
3
4
5
<dependency>
     <groupId>org.quartz-scheduler</groupId>
     <artifactId>quartz</artifactId>
     <version>${quartz.version}</version>
   </dependency>

三、整合实现

1、spring配置

spring只需要添加quartz调度工厂bean就可以了

 

复制代码 代码如下:

<bean id="schedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" />

 

 2、定时器工作类实现

定义定时器作业类,该类继承自job类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.ld.nhmz.quartz;
 
import java.text.SimpleDateFormat;
import java.util.Date;
 
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
 
/**
 * quartz示例定时器类
 *
 * @author Administrator
 *
 */
public class QuartzJobExample implements Job {
  @Override
  public void execute(JobExecutionContext arg0) throws JobExecutionException {
    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "★★★★★★★★★★★");
  }
}

定义定时器管理类

?
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
package com.ld.nhmz.quartz;
 
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
 
/**
 * Quartz调度管理器
 *
 * @author Administrator
 *
 */
public class QuartzManager {
  private static String JOB_GROUP_NAME = "EXTJWEB_JOBGROUP_NAME";
  private static String TRIGGER_GROUP_NAME = "EXTJWEB_TRIGGERGROUP_NAME";
 
  /**
   * @Description: 添加一个定时任务,使用默认的任务组名,触发器名,触发器组名
   *
   * @param sched
   *      调度器
   *
   * @param jobName
   *      任务名
   * @param cls
   *      任务
   * @param time
   *      时间设置,参考quartz说明文档
   *
   * @Title: QuartzManager.java
   */
  public static void addJob(Scheduler sched, String jobName, @SuppressWarnings("rawtypes") Class cls, String time) {
    try {
      JobDetail jobDetail = new JobDetail(jobName, JOB_GROUP_NAME, cls);// 任务名,任务组,任务执行类
      // 触发器
      CronTrigger trigger = new CronTrigger(jobName, TRIGGER_GROUP_NAME);// 触发器名,触发器组
      trigger.setCronExpression(time);// 触发器时间设定
      sched.scheduleJob(jobDetail, trigger);
      // 启动
      if (!sched.isShutdown()) {
        sched.start();
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
 
  /**
   * @Description: 添加一个定时任务
   *
   * @param sched
   *      调度器
   *
   * @param jobName
   *      任务名
   * @param jobGroupName
   *      任务组名
   * @param triggerName
   *      触发器名
   * @param triggerGroupName
   *      触发器组名
   * @param jobClass
   *      任务
   * @param time
   *      时间设置,参考quartz说明文档
   *
   * @Title: QuartzManager.java
   */
  public static void addJob(Scheduler sched, String jobName, String jobGroupName, String triggerName, String triggerGroupName, @SuppressWarnings("rawtypes") Class jobClass, String time) {
    try {
      JobDetail jobDetail = new JobDetail(jobName, jobGroupName, jobClass);// 任务名,任务组,任务执行类
      // 触发器
      CronTrigger trigger = new CronTrigger(triggerName, triggerGroupName);// 触发器名,触发器组
      trigger.setCronExpression(time);// 触发器时间设定
      sched.scheduleJob(jobDetail, trigger);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
 
  /**
   * @Description: 修改一个任务的触发时间(使用默认的任务组名,触发器名,触发器组名)
   *
   * @param sched
   *      调度器
   * @param jobName
   * @param time
   *
   * @Title: QuartzManager.java
   */
  @SuppressWarnings("rawtypes")
  public static void modifyJobTime(Scheduler sched, String jobName, String time) {
    try {
      CronTrigger trigger = (CronTrigger) sched.getTrigger(jobName, TRIGGER_GROUP_NAME);
      if (trigger == null) {
        return;
      }
      String oldTime = trigger.getCronExpression();
      if (!oldTime.equalsIgnoreCase(time)) {
        JobDetail jobDetail = sched.getJobDetail(jobName, JOB_GROUP_NAME);
        Class objJobClass = jobDetail.getJobClass();
        removeJob(sched, jobName);
        addJob(sched, jobName, objJobClass, time);
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
 
  /**
   * @Description: 修改一个任务的触发时间
   *
   * @param sched
   *      调度器 *
   * @param sched
   *      调度器
   * @param triggerName
   * @param triggerGroupName
   * @param time
   *
   * @Title: QuartzManager.java
   */
  public static void modifyJobTime(Scheduler sched, String triggerName, String triggerGroupName, String time) {
    try {
      CronTrigger trigger = (CronTrigger) sched.getTrigger(triggerName, triggerGroupName);
      if (trigger == null) {
        return;
      }
      String oldTime = trigger.getCronExpression();
      if (!oldTime.equalsIgnoreCase(time)) {
        CronTrigger ct = (CronTrigger) trigger;
        // 修改时间
        ct.setCronExpression(time);
        // 重启触发器
        sched.resumeTrigger(triggerName, triggerGroupName);
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
 
  /**
   * @Description: 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
   *
   * @param sched
   *      调度器
   * @param jobName
   *
   * @Title: QuartzManager.java
   */
  public static void removeJob(Scheduler sched, String jobName) {
    try {
      sched.pauseTrigger(jobName, TRIGGER_GROUP_NAME);// 停止触发器
      sched.unscheduleJob(jobName, TRIGGER_GROUP_NAME);// 移除触发器
      sched.deleteJob(jobName, JOB_GROUP_NAME);// 删除任务
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
 
  /**
   * @Description: 移除一个任务
   *
   * @param sched
   *      调度器
   * @param jobName
   * @param jobGroupName
   * @param triggerName
   * @param triggerGroupName
   *
   * @Title: QuartzManager.java
   */
  public static void removeJob(Scheduler sched, String jobName, String jobGroupName, String triggerName, String triggerGroupName) {
    try {
      sched.pauseTrigger(triggerName, triggerGroupName);// 停止触发器
      sched.unscheduleJob(triggerName, triggerGroupName);// 移除触发器
      sched.deleteJob(jobName, jobGroupName);// 删除任务
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
 
  /**
   * @Description:启动所有定时任务
   *
   * @param sched
   *      调度器
   *
   * @Title: QuartzManager.java
   */
  public static void startJobs(Scheduler sched) {
    try {
      sched.start();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
 
  /**
   * @Description:关闭所有定时任务
   *
   *
   * @param sched
   *      调度器
   *
   *
   * @Title: QuartzManager.java
   */
  public static void shutdownJobs(Scheduler sched) {
    try {
      if (!sched.isShutdown()) {
        sched.shutdown();
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}

 测试代码,这里SchedulerFactory没有使用spring中配置的bean,而是new出来的,做测试用

?
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
package com.ld.nhmz.quartz.test;
 
import org.junit.Test;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
 
import com.ld.nhmz.quartz.QuartzJobExample;
import com.ld.nhmz.quartz.QuartzManager;
 
/**
 * @Description: 测试类
 *
 * @ClassName: QuartzTest.java
 */
public class QuartzTest {
  @Test
  public void quartz() {
    try {
      SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
      Scheduler sche = gSchedulerFactory.getScheduler();
      String job_name = "动态任务调度";
      System.out.println("【系统启动】开始(每1秒输出一次)...");
      QuartzManager.addJob(sche, job_name, QuartzJobExample.class, "0/1 * * * * ?");
 
      Thread.sleep(3000);
      System.out.println("【修改时间】开始(每2秒输出一次)...");
      QuartzManager.modifyJobTime(sche, job_name, "10/2 * * * * ?");
      Thread.sleep(4000);
      System.out.println("【移除定时】开始...");
      QuartzManager.removeJob(sche, job_name);
      System.out.println("【移除定时】成功");
 
      System.out.println("【再次添加定时任务】开始(每10秒输出一次)...");
      QuartzManager.addJob(sche, job_name, QuartzJobExample.class, "*/10 * * * * ?");
      Thread.sleep(30000);
      System.out.println("【移除定时】开始...");
      QuartzManager.removeJob(sche, job_name);
      System.out.println("【移除定时】成功");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

显示结果:

Spring整合Quartz实现动态定时器的示例代码

spring Control层代码中实现定时器管理

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/xrab/p/5850186.html