quartz定时调度实例
最近弄了个Quartz定时调度的例子,不是很难,但也写出来来分享一下,由于本人一直在用Struts 2.1.8 +Spring2.5+Hibernate3(SSH2)做开发,所以这个实例也是基于SSH2的,以及所导入的JAR也是基于SSH2 的,网上有很多人说
用Spring2.5做会出错,但是我这里是一切正常。OK,看实例。
?
首先,准备相关jar库文件:
?一个是quartz-all-1.6.5.jar
?一个是spring.jar
特别是后面这个spring核心包,在我之前做的SSH2框架里是没有导入这个包的,因为没有用到,但是在使用Quartz时一定要导入这个包,Quartz的部分操作依赖于这个包。我为此郁闷了老半天。
相关下载地址在网上比较难找,我不记得上次是怎么下到的了,好像是从CSDN吧,现在直接打包在项目里提供给大家吧,当然,这是一种不好的习惯,大家不要学我啊。嘻嘻~~~
?
?
?
1、web.xml
?
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" 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"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>contextConfigLocation</param-name> <param-value> WEB-INF/classes/applicationContext-*.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>
?
在web.xml中,其实Quartz只需要和Sping相关的配置就可以了,我这里多配置了Struts 2的。这个不影响。
?
2、applicationContext-struts.xml
?
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- 要调用的工作类 --> <bean id="quartzJob" lazy-init="false" autowire="no" name="code">/** * @author 小敏 *2012-10-12 下午02:54:16 */package org.yzsoft.quartz.test;/** * @author 小敏 创建时间: 2012-10-12 下午02:54:16 * */public class Test {public void test() {System.out.println("123541");}}
?
?
?
很简单的一个测试类,运行后我们可以看到,控制台输出了我们的测试信息:
123541123541123541123541123541123541
?
这就表示我们定时调度执行成功了。
?
定时调度作为一个组件可以应用在很多方面,比如说工作流中的定时插数据管理考勤、定时数据备份以及各种系统的业务需要,
这里只作一个最简单的应用,其实Quartz还可以自己定义quartz.properties和quartz_reminder.xml等配置文件,看具体业务需求,如各位有需要可以参考一下这方面的文档和教程。
?
Quartz还有很多高级的功能实现 ,也许我们现在用的冰山一角都不到,但还是觉得,技术的东西很多 ,我们不可能每一种都学完都用完,取其所长,为我所用,就足够了。
?
?
最后 ,附上整个项目源码。
?