在JavaEE系統中,咱們會常常用到定時任務,下面是我本身寫的一個demo.java
源碼地址:http://pan.baidu.com/s/1BXHv3web
1.所須要的jarspring
2.實體bean併發
package cn.zyc.quartz; import java.util.Date; public class Study { public void doStudy() { System.out.println("It is " + new Date()); } }
3.applicationContext.xmlapp
<?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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 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/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"> <!-- bean --> <bean id="study" class="cn.zyc.quartz.Study" /> <!-- 定義調用對象和調用對象的方法 --> <bean id="studyDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <!-- 調用的類 --> <property name="targetObject" ref="study" /> <!-- 調用類中的方法 --> <property name="targetMethod" value="doStudy" /> <!-- 是否容許任務併發執行。當值爲false時,表示必須等到前一個線程處理完畢後纔再啓一個新的線程 --> <property name="concurrent" value="false"/> </bean> <!-- quartz-1.8之前的配置 <bean id="myJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail"> <ref bean="studyDetail" /> </property> <property name="cronExpression"> <value>0/1 * * * * ?</value> </property> </bean> --> <!-- quartz-2.x的配置 --> <!-- 定義觸發時間 --> <bean id="myJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail"> <ref bean="studyDetail" /> </property> <property name="cronExpression"> <value>0/5 * * * * ?</value> </property> </bean> <!-- 總管理類 若是將lazy-init='false'那麼容器啓動就會執行調度程序 --> <!-- 若是lazy-init='true',則須要實例化該bean才能執行調度程序 --> <bean name="startQuertz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="myJobTrigger" /> </list> </property> <!-- <property name="autoStartup" value="true"/> --> </bean> </beans>
4.web.xml.net
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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_3_0.xsd"> <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> </web-app>