您的位置:首页 > 编程语言 > Java开发

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

2013-08-13 11:43 295 查看
首先,要熟悉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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: