Spring整理系列(08)——spring与quartz整合执行定时任务

项目基于maven进行管理。

一、实例项目代码示例:
1、pom.xml文件所需要的基本jar:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>

  <groupId>com.test.springgroupId>
  <artifactId>supportartifactId>
  <version>0.0.1-SNAPSHOTversion>
  <packaging>jarpackaging>

  <name>supportname>
  <url>http://maven.apache.orgurl>

  <properties>
    <spring.version>4.2.6.RELEASEspring.version>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
  properties>

  <dependencies>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-contextartifactId>
        <version>${spring.version}version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-context-supportartifactId>
        <version>${spring.version}version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-txartifactId>
        <version>${spring.version}version>
    dependency>
    
    <dependency>
        <groupId>org.quartz-schedulergroupId>
        <artifactId>quartzartifactId>
        <version>2.1.3version>
    dependency>
    

    
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        
        <version>4.11version>
        <scope>testscope>
    dependency> 
  dependencies>
project>

2、src/main/resources下spring-context.xml文件,包含定时器调度配置:


<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:task="http://www.springframework.org/schema/task" 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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd
        http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd" default-lazy-init="false">

    
    <context:component-scan base-package="com.test.spring.support">context:component-scan>

    
    

    
    <bean id="doJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        
        <property name="targetObject">
            <ref bean="testQuartTimer" />
        property>
        
        <property name="targetMethod">
            <value>testQuartTimerMethodvalue>
        property>
    bean>

    
    
    <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail">
            <ref bean="doJob" />
        property>
        <property name="cronExpression">
            
            <value>0/10 * * * * ?value>
        property>
    bean>

    
    
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="cronTrigger" />
            list>
        property>
    bean>
beans>

3、src/main/java下创建com.test.spring.support.TestQuartTimer类,作为定时器,执行主方法即可调用定时任务:

package com.test.spring.support;

import java.util.Scanner;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

/**
 * 测试定时器
 */
@Service
@Lazy(false)
public class TestQuartTimer {

    /**
     * @Date 创建时间:2016年8月9日 下午4:47:05
     * @Description :定时任务执行
     */
    public void testQuartTimerMethod(){
        System.out.println("testQuartTimerMethod 定时任务执行中...");
    }

    /**
     * @Description :主方法测试Quart定时任务
     */
    public static void main(String[] args){

        ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-context.xml");

        //测试定时任务,阻塞主方法结束
        Scanner input=new Scanner(System.in);
        input.nextInt();
    }
}

4、src/test/java下创建com.test.spring.support.TestSpringContextHolder类,通过单元测试执行定时器:

package com.test.spring.support;

import java.util.Scanner;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 单元测试类
 */
public class TestSpringContextHolder{

    @Test
    public void testQuartzTime(){
        //测试定时任务,阻塞单元测试方法结束
        Scanner input=new Scanner(System.in);
        int x=input.nextInt();
    }

    //以下为容器实例声明及初始化、销毁
    private ClassPathXmlApplicationContext context;

    @Before
    public void before(){

        try {
            // xml文件用逗号或者空格符隔开,均可加载
            context = new ClassPathXmlApplicationContext("spring-context.xml");
            context.start();

        } catch (BeansException e) {
            e.printStackTrace();
        }
    }
    @After
    public void after(){
        context.destroy();
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    @SuppressWarnings("unchecked")
    public  T getBean(String name) {
        return (T) context.getBean(name);
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public  T getBean(Class requiredType) {
        return context.getBean(requiredType);
    }
}

5、如果web环境,需要servlet容器加载spring容器(同时注意添加spring web jar):

  
<web-app xmlns="http://java.sun.com/xml/ns/javaee"  
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  
          http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
         version="2.5">  
    <welcome-file-list>  
        <welcome-file>index.htmlwelcome-file>  
    welcome-file-list>  

    <context-param>  
        <param-name>contextConfigLocationparam-name>  
        <param-value>/WEB-INF/spring-config.xmlparam-value>  
    context-param>  

    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>  
    listener>  
web-app>

上述代码包测试地址:http://download.csdn.net/detail/javaloveiphone/9599194
上面实例以及下面将要介绍的quartz版本问题参照:http://kevin19900306.iteye.com/blog/1397744?page=2



二、触发器的执行周期表达式cronExpression:
Spring整理系列(09)——spring与quartz整合触发器执行表达式cronExpression详解




三、实例测试过程中发生的几个异常

1、Spring与Quartz的版本问题,发生异常如下:

Caused by: java.lang.ClassNotFoundException: org.springframework.scheduling.quartz.CronTriggerBean

原因是Spring 3.0版本中内置的Quartz版本是<2.0的,在使用最新的Quartz包(>2.0)之后,出现版本不兼容问题。

解决办法有两种:

1)、降低Quartz版本,降到1.X去,比如1.8.5,触发器的bean使用**TriggerBean,比如org.springframework.scheduling.quartz.CronTriggerBean

2)、升级Spring版本到3.1+或4.x,将原来的**TriggerBean替换成**TriggerFactoryBean,例如org.springframework.scheduling.quartz.CronTriggerBean 就可以替换成 org.springframework.scheduling.quartz.CronTriggerFactoryBean,替换之后问题解决。




2、异常如下:

Exception in thread "main" java.lang.NoClassDefFoundError: org/quartz/impl/JobDetailImpl
Caused by: java.lang.ClassNotFoundException: org.quartz.impl.JobDetailImpl

原因是quartz低版本中缺少JobDetailImpl这个类。
解决办法是将quartz版本从1.x提高到2.x,测试2.1.3是没有问题的。



3、异常如下:

java.lang.NoClassDefFoundError: org/springframework/transaction/TransactionException
Caused by: java.lang.ClassNotFoundException: org.springframework.transaction.TransactionException

原因是缺少spring的TransactionException类,即缺少spring框架相关jar包。
解决方法是添加org.springframework.spring-tx-3.1.1.RELEASE.jar,pom.xml文件:

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-txartifactId>
        
        <version>${spring.version}version>
    dependency>

你可能感兴趣的:(Spring)