Java 定时器 Quzrtz 的集成使用
1. 实现思路
1) 导入依赖Jar包(Spring和Quartz)
2) 编写定时任务(TestJob 类)
3) 配置Spring参数,配置定时任务的运行时间
4) 编写测试用例,运行测试、输出测试结果
2. 引入Maven 依赖包
2.1. 引入Spring 和 Quartz
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.2</version>
</dependency>
3. 代码片段
3.1. 作业任务代码
package test.cn.lwz.timer;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
/**
* 测试使用的作业任务
* @author LiWenZhang
* @date 2016-02-19 16:21:28
*/
public class TestJob extends QuartzJobBean {
protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException {
System.out.println("TestJob.executeInternal(JobExecutionContext) ...");
// 作业任务内容…
}
}
3.2. 测试类(Tests)
package test.cn.lwz;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 测试用例
* @author LiWenZhang
* @date 2016-02-19 17:13:18
*/
public class Tests {
@Test
public void testQuartz() throws Exception {
try (ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("/spring/test-quartz-context.xml")) {
Thread.sleep(100000);
}
}
}
4. 配置文件
4.1. Spring 配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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-2.5.xsd">
<bean name="exampleJob"
class="org.springframework.scheduling.quartz.JobDetailFactoryBean">
<property name="jobClass" value="test.cn.lwz.timer.TestJob" />
</bean>
<bean id="cronTrigger"
class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<!-- 作业任务 -->
<property name="jobDetail" ref="exampleJob" />
<!-- 执行触发表达式 -->
<property name="cronExpression" value="0/5 * * * * ?" />
</bean>
<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronTrigger" />
</list>
</property>
</bean>
</beans>
5. 运行结果输出
版权声明:本文为Li_WenZhang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。