Spring2.0集成Quartz1.5.2调度框架

  Quartz是个开放源码项目,提供了丰富的作业调度集。希望您在阅读完本文并看过代码演示后,可以把Quartz的基本特性应用到任何Java™应用程序中。
现代的Web应用程序框架在范围和复杂性方面都有所发展,应用程序的每个底层组件也必须相应地发展。作业调度是现代系统中对Java应用程序的一般要求,而且也是对Java开发人员一贯的要求。虽然目前的调度技术比起原始的数据库触发器标志和独立的调度器线程来说,已经发展了许多,但是作业调度仍然不是个小问题。对这个问题最合适的解决方案就是来自OpenSymphony的QuartzAPI。
  Quartz是个开源的作业调度框架,为在Java应用程序中进行作业调度提供了简单却强大的机制。Quartz允许开发人员根据时间间隔(或天)来调度作业。它实现了作业和触发器的多对多关系,还能把多个作业与不同的触发器关联。整合了Quartz的应用程序可以重用来自不同事件的作业,还可以为一个事件组合多个作业。虽然可以通过属性文件(在属性文件中可以指定JDBC事务的数据源、全局作业和/或触发器侦听器、插件、线程池,以及更多)配置Quartz,但它根本没有与应用程序服务器的上下文或引用集成在一起。结果就是作业不能访问Web服务器的内部函数;例如,在使用IBMWebSphere应用服务器时,由Quartz调度的作业并不能影响服务器的动态缓存和数据源。

下面是在spring下的quartz调用过程。

一、首先是一些基本工作:

1、引入jar包,对应spring2.0对quartz的集成版本是quartz1.5.2版本,如果quartz过高的话是不支持的。

jar如下:

  commons-logging.jar

  log4j-1.2.15.jar

  quartz-1.5.2.jar

  spring.jar

只需要添加这4个jar足已。

2、在web.xml中配置spring监听。

<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
</context-param>

二、下面是代码的编写。

1、需要创建一个任务调用类,用于quartz调用。

package quartz;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MySchedu {
  public static void main(String[] args) {
    System.out.println("Test start ...... ");
    new ClassPathXmlApplicationContext("applicationContext.xml");
    System.out.print("Test end ...... ");
  }
}

2、在applicationContext.xml文件中添加quartz的配置。

<?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.0.xsd">

<bean id="myJob" class="quartz.MyJob"></bean>

<!-- 定义目标bean和bean中的方法 -->
<bean id="Job" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject">
<ref local="myJob" />
</property>
<property name="targetMethod">
<!-- 要执行的方法名称 -->
<value>work</value>
</property>
</bean>

<!--定义触发的时间-->
<bean id="cron" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="Job" />
</property>
<property name="cronExpression">
<value>0-59 * * * * ?</value>
</property>
</bean>

<!-- 管理触发器 -->
<bean autowire="no"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref local="cron" />
</list>
</property>
</bean>
</beans>

原文地址:https://www.cnblogs.com/zhilongblogs/p/3898841.html