Java 定时器 Quzrtz 的集成使用

Java 定时器 Quzrtz 的集成使用

1. 实现思路

1) 导入依赖Jar包(Spring和Quartz)
2) 编写定时任务(TestJob 类)
3) 配置Spring参数,配置定时任务的运行时间
4) 编写测试用例,运行测试、输出测试结果

2. 引入Maven 依赖包

2.1. 引入Spring 和 Quartz

<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-coreartifactId>
    <version>4.1.8.RELEASEversion>
dependency>
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-contextartifactId>
    <version>4.1.8.RELEASEversion>
dependency>
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-beansartifactId>
    <version>4.1.8.RELEASEversion>
dependency>
<dependency>
    <groupId>org.springframeworkgroupId>
    <artifactId>spring-context-supportartifactId>
    <version>4.1.8.RELEASEversion>
dependency>

<dependency>
    <groupId>org.quartz-schedulergroupId>
    <artifactId>quartzartifactId>
    <version>2.2.2version>
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 配置



<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. 运行结果输出

Java 定时器 Quzrtz 的集成使用_第1张图片

你可能感兴趣的:(JavaEE,Spring,Quzrtz,Maven)