下面介绍Spring集成Quartz的示例,项目地址: quartz-spring
介绍Spring和Quartz集成存储方式使用的是RAM方式和JDBC方式!

jar包依赖

<properties>
    <!-- 项目构建源码编码方式 -->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <!-- 主要依赖库的版本定义 -->
    <!-- spring版本号 -->
    <spring.version>4.0.2.RELEASE</spring.version>
    <!-- 日志文件管理包版本 -->
    <slf4j.version>1.7.7</slf4j.version>
    <junit.version>4.11</junit.version>
    <jackson.version>2.4.0</jackson.version>
    <mysql.version>5.1.30</mysql.version>
    <quartz.version>2.2.3</quartz.version>
    <fastjson.version>1.1.41</fastjson.version>

</properties>


<dependencies>

    <!-- spring核心包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-oxm</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</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-aop</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <!-- 导入java ee jar 包 -->
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>
    <!-- JSTL标签类 -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <!-- 日志文件管理包 -->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.1.3</version>
    </dependency>
    <dependency>
        <groupId>org.logback-extensions</groupId>
        <artifactId>logback-ext-spring</artifactId>
        <version>0.1.2</version>
    </dependency>
    <!-- 代码直接调用commons-logging会被桥接到slf4j -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.12</version>
    </dependency>
    <!-- 代码直接调用java.util.logging会被桥接到slf4j -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jul-to-slf4j</artifactId>
        <version>1.7.12</version>
    </dependency>
    <!-- 格式化对象,方便输出日志 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>${fastjson.version}</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>
    <!-- 导入Mysql数据库链接jar包 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql.version}</version>
    </dependency>
    <!-- velocity -->
    <dependency>
        <groupId>org.apache.velocity</groupId>
        <artifactId>velocity</artifactId>
        <version>1.7</version>
    </dependency>

    <dependency>
        <groupId>org.apache.velocity</groupId>
        <artifactId>velocity-tools</artifactId>
        <version>2.0</version>
    </dependency>


    <!-- JSON begin -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.module</groupId>
        <artifactId>jackson-module-jaxb-annotations</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <!-- freemarker -->
    <dependency>
        <groupId>org.freemarker</groupId>
        <artifactId>freemarker</artifactId>
        <version>2.3.27-incubating</version>
    </dependency>

    <dependency>
        <groupId>org.quartz-scheduler</groupId>
        <artifactId>quartz</artifactId>
        <version>${quartz.version}</version>
    </dependency>
    <dependency>
        <groupId>org.quartz-scheduler</groupId>
        <artifactId>quartz-jobs</artifactId>
        <version>${quartz.version}</version>
    </dependency>
</dependencies>

配置文件spring-quartz.xml

RAM存储方式的xml配置文件

(1):配置文件

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
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- ====================================RAM版============================================== -->
<!--
Spring整合Quartz进行配置遵循下面的步骤:
1:定义工作任务的Job
2:定义触发器Trigger,并将触发器与工作任务绑定
3:定义调度器,并将Trigger注册到Scheduler
-->
<!-- 1:定义任务的bean ,这里使用JobDetailFactoryBean,也可以使用MethodInvokingJobDetailFactoryBean ,配置类似-->
<bean name="hwJob" class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<!-- 指定job的名称 -->
<property name="name" value="hw_job"/>
<!-- 指定job的分组 -->
<property name="group" value="hw_group"/>
<!-- 指定具体的job类 -->
<property name="jobClass" value="com.wyj.exampleRAM.RAMJob"/>
<!-- 必须设置为true,如果为false,当没有活动的触发器与之关联时会在调度器中会删除该任务 -->
<property name="durability" value="true"/>
<!-- 指定spring容器的key,如果不设定在job中的jobmap中是获取不到spring容器的 -->
<property name="applicationContextJobDataKey" value="applicationContext"/>
</bean>
<!-- 2.1:定义触发器的bean,定义一个Simple的Trigger,一个触发器只能和一个任务进行绑定 -->
<!-- <bean name="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean">
指定Trigger的名称
<property name="name" value="hw_trigger"/>
指定Trigger的名称
<property name="group" value="hw_trigger_group"/>
指定Tirgger绑定的Job
<property name="jobDetail" ref="hwJob"/>
指定Trigger的延迟时间 1s后运行
<property name="startDelay" value="1000"/>
指定Trigger的重复间隔 5s
<property name="repeatInterval" value="5000"/>
指定Trigger的重复次数
<property name="repeatCount" value="5"/>
</bean> -->
<!-- 2.2:定义触发器的bean,定义一个Cron的Trigger,一个触发器只能和一个任务进行绑定 -->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<!-- 指定Trigger的名称 -->
<property name="name" value="hw_trigger"/>
<!-- 指定Trigger的名称 -->
<property name="group" value="hw_trigger_group"/>
<!-- 指定Tirgger绑定的Job -->
<property name="jobDetail" ref="hwJob"/>
<!-- 指定Cron 的表达式 ,当前是每隔1s运行一次 -->
<property name="cronExpression" value="0/1 * * * * ?" />
</bean>
<!-- 3.定义调度器,并将Trigger注册到调度器中-->
<bean name="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<!-- <ref bean="simpleTrigger"/> -->
<ref bean="cronTrigger"/>
</list>
</property>
</bean>
</beans>

(2):运行结果
CronScheduleBuilder:
RAMTest

JDBC存储方式的xml配置文件

(1):配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- ====================================JDBC版============================================== -->
<!--
持久化数据配置,需要添加quartz.properties
-->
<bean name="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="applicationContextSchedulerContextKey" value="applicationContextKey"/>
<property name="configLocation" value="classpath:quartz.properties"/>
</bean>
</beans>

(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
26
27
28
29
30
31
32
33
34
35
36
# 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.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
#JDBC连接方式
org.quartz.jobStore.class: org.quartz.impl.jdbcjobstore.JobStoreTX
#JDBC代理类
org.quartz.jobStore.driverDelegateClass: org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.useProperties:true
#指定前缀
org.quartz.jobStore.tablePrefix: QRTZ_
#数据源名称
org.quartz.jobStore.dataSource: qzDS
#配置数据源属性
org.quartz.dataSource.qzDS.driver:com.mysql.jdbc.Driver
org.quartz.dataSource.qzDS.URL:jdbc:mysql://192.168.99.100:3306/quartz_test?useUnicode=true&characterEncoding=utf-8
org.quartz.dataSource.qzDS.user:root
org.quartz.dataSource.qzDS.password:admin
org.quartz.dataSource.qzDS.maxConnections:10

(3):job

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
package com.wyj.exampleJDBC;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* JdbcJob
*
*
* @author:WangYuanJun
* @date:2017年12月29日 下午10:05:18
*/
public class JdbcJob implements Job{
private Logger logger = LoggerFactory.getLogger(JdbcJob.class);
public void execute(JobExecutionContext arg0) throws JobExecutionException {
logger.debug("MyJDBCJob is start ...");
logger.debug("MyJDBCJob quzrtz "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(new Date()));
logger.debug("MyJDBCJob is end ...");
}
}

(4):jobTest

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
package com.wyj.exampleJDBC;
import java.util.List;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdScheduler;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* JdbcJobtest
*
*
* @author:WangYuanJun
* @date:2017年12月29日 下午10:05:26
*/
public class QuartzJdbcTest {
private static Scheduler scheduler;
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("spring-quartz.xml");
scheduler = (StdScheduler)ac.getBean("scheduler");
testStartSchedule();
}
/**
* 开始一个simpleSchedule()调度
*/
public static void testStartSchedule(){
try {
// 1、创建一个JobDetail实例,指定Quartz
JobDetail jobDetail = JobBuilder.newJob(JdbcJob.class)
// 任务执行类
.withIdentity("job_1", "jGroup1")// 任务名,任务组
.build();
//触发器类型
//SimpleScheduleBuilder builder = SimpleScheduleBuilder.simpleSchedule().repeatSecondlyForTotalCount(5); // 设置执行次数
CronScheduleBuilder builder = CronScheduleBuilder.cronSchedule("0/2 * * * * ?");
// 2、创建Trigger
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("trigger_1","triggerGroup1")
.withSchedule(builder)
.build();
// 3、创建Scheduler
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
// 4、调度执行
scheduler.scheduleJob(jobDetail,trigger);
try {
Thread.sleep(60000);
} catch (Exception e) {
e.printStackTrace();
}
//关闭调度器
scheduler.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 从数据库中找到已经存在的job,并重新开户调度
*/
public static void resumeJob(){
try {
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
JobKey jobKey = new JobKey("job1_1", "jGroup1");
List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
//SELECT TRIGGER_NAME, TRIGGER_GROUP FROM {0}TRIGGERS WHERE SCHED_NAME = {1} AND JOB_NAME = ? AND JOB_GROUP = ?
// 重新恢复在jGroup1组中,名为job1_1的 job的触发器运行
if(triggers.size() > 0){
for (Trigger tg : triggers) {
// 根据类型判断
if ((tg instanceof CronTrigger) || (tg instanceof SimpleTrigger)) {
// 恢复job运行
scheduler.resumeJob(jobKey);
}
}
scheduler.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

运行结果:
CronScheduleBuilder:
jdbcTest