Quartz定时任务在Spring MVC 中的实现

来源:互联网 发布:深入浅出数据分析 epub 编辑:程序博客网 时间:2024/05/05 06:03
首先,要熟悉spring mvc的工作原理。在这里,只搭建一个简单的页面跳转的MVC实现。 
需要注意的是spring 3并不能和最新 的Quartz结合,需要,在此采用的比 新的Quartz 1.7。 
Task.java可以是任何java类,其中至少 包括一个可执行的方法。 (原因见task-config.xml) 

 
task-config.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:jee="http://www.springframework.org/schema/jee"  xmlns:tx="http://www.springframework.org/schema/tx" 
xmlns:context="http://www.springframework.org/schema/context"  xmlns:aop="http://www.springframework.org/schema/aop" 
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  http://www.springframework.org/schema/jee 
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd  http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.0.xsd"  default-autowire="byName" default-lazy-init="false"> 
 
 <!-- 要调用的工作类 --> 

 <bean id="quartzJob" class="com.tasks.Task"></bean>

<!-- 定义调用对象和调用对象的方法 -->

<bean id="jobtask"  class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> 

<!-- 调用的类 --> 
<property name="targetObject">    <ref bean="quartzJob" />   </property> 
  <!-- 调用类中的方法 --> 

  <property name="targetMethod">    <value>main</value>   </property>

</bean> 

  <!-- 定义触发时间 -->  

<bean id="doTime"  class="org.springframework.scheduling.quartz.CronTriggerBean"> 

<property name="jobDetail">    <ref bean="jobtask" />   </property> 

  <!-- cron表达式 --> 
  <property name="cronExpression"> 

    <value>10,15,20,25,30,35,40,45,50,55 * * * * ?</value>

</property>

</bean> 

  <!-- 总管理类 如果将lazy-init='false'那么容器启动就会执行调度程序 --> 

  <bean id="startQuertz" lazy-init="false" autowire="no"  class="org.springframework.scheduling.quartz.SchedulerFactoryBean">

<property name="triggers">

<list> 

    <ref bean="doTime" /> 

</list> 

</property>

 </bean> 

</beans> 


在web.xml里load这个配置: 
<context-param> 

<param-name>contextConfigLocation</param-name>

<param-value> /WEB-INF/task-config.xml   </param-value>

</context-param>

<listener> 

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

</listener>

原创粉丝点击