使用spring+quartz配置多个定时任务
转:https://blog.csdn.net/pansanday/article/details/42466173
Spring被用在了越来越多的项目中, quartz也被公认为是比较好用的定时器设置工具, 在这里通过一个demo说明如何使用spring和quartz配置多个定时任务.
环境: eclipse + maven + spring 3.0.6.RELEASE版本 + quartz 1.8.6版本
一. 准备工作
项目目录结构截图:
需要引入的jar包, 这里是采用maven的dependency依赖; 如果没有使用maven, 可以对照着上面的jar包截图一一进行下载. 这里唯一需要注意的就是, 如果使用spring 3.1以下的版本, quartz就需要相应的2.0以下版本, 否则会导致 org.springframework.beans.factory.CannotLoadBeanClassException: Error loading class [org.springframework.scheduling.quartz.CronTriggerBean] for bean with name 'cronTrigger_1' defined in file [E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\git-common\WEB-INF\classes\applicationContext.xml]: problem with class file or dependent class; nested exception isjava.lang.IncompatibleClassChangeError: class org.springframework.scheduling.quartz.CronTriggerBean has interface org.quartz.CronTrigger as super class错误.
后续: 后来使用了spring 4.0.5.RELEASE版本+quartz 2.2.1版本, 还是报出了以上错误, 将quartz降低为1.8.6版本后, 问题消失...
3.0.6.RELEASE
javax.servlet
servlet-api
2.5
provided
org.springframework
spring-context
${springframework.version}
org.springframework
spring-context-support
${springframework.version}
org.springframework
spring-tx
${springframework.version}
org.springframework
spring-web
${springframework.version}
org.quartz-scheduler
quartz
1.8.6
二. 程序代码及配置代码
测试代码就简单的打印出一句话
packagecom.quartz.demo;
importjava.util.Date;
publicclassJob1Demo{
publicvoidsayHello(){
System.out.println(newDate() +" -> Hello, 我是任务 1");
}
}
packagecom.quartz.demo;
importjava.util.Date;
publicclassJob2Demo{
publicvoidsayHello(){
System.out.println(newDate() +" -> Hello, 我是任务 2");
}
}
Spring配置文件applicationContext.xml中配置了要注入的bean, 定时任务, 任务执行周期时间等
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
sayHello
0/1 * * * * ?
sayHello
0/1 * * * * ?
web.xml, 在spring容器启动时读取加载applicationContext.xml配置文件
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
Archetype Created Web Application
contextConfigLocation
classpath:*.xml
org.springframework.web.context.ContextLoaderListener
三. 执行结果
将web项目部署到tomcat等容器中, 启动后, 就可以看到定时器执行效果, 如下图所示