使用的版本Spring4.04+Quartz2.2.3,關於jar包自行下載。
詳細需要以下幾個步驟來完成:
1. 定義要執行的Job類
2. 定義quartz的配置文件applicationContext-quartz.xml
2.1 定義要調用的對象和對象的方法
2.2 在觸發器中配置使用該方法的時間
2.3 在總管類中添加該任務
3. 定義執行的任務的時間配置文件
4. 在攔截器中添加要掃描的包
5. 將quartz配置文件添加到我們的spring容器的配置文件applicationContext.xml中
6. 啟動tomcat
下面以具體實例來演示:
1. 定義要執行的Job類 TestJob.java
注意加上注解標記該類為Component組件,這樣方便自動裝配到spring容器中管理。
package com.crm.scheduler; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component("testJobComponent") public class TestJob { //定義是否 @Value("${crmbi.cronExpression.isDoTestJob}") private boolean isDoTestJob = false; public void execute(){ if(!isDoTestJob){ return ; } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println("我是定時任務類,現在的執行時間是" + sdf.format(new Date())); } }
2. 定義quartz的配置文件
2.1 定義要調用的對象和對象的方法,在這里對象就是上面的新建的testJobComponnent。
<!-- 定時器2:測試quartz類的使用方法 --> <!-- 定義調用的對象及對象中的方法 --> <bean id="defTestJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="testJobComponent" /> <property name="targetMethod" value="execute" /> <property name="concurrent" value="false" /> <!-- 是否支持並發 --> </bean>
2.2 定義觸發器並配置定時任務執行的時間
<!-- 觸發器:定義出發器執行的腳本的時間 --> <bean id="triggerTestJob" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail" ref="defTestJob" /> <property name="cronExpression"> <value>${crmbi.cronExpression.testJob}</value> </property> </bean>
2.3 在總管理中添加該任務
<!-- 總管理類,啟動觸發器的配置, 如果將lazy-init='false'那么容器啟動就會執行調度程序 --> <bean id="startQuartz" lazy-init='false' autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="triggerTestjob" /> </list> </property> <property name="autoStartup" value="true" /> <property name="startupDelay" value="30"/> </bean>
最后展示下完成的配置文件applicationContext-quartz.xml如下,其中包含了2個定時任務類,triggerTestJob為我們新增的任務信息:
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:task="http://www.springframework.org/schema/task" xmlns:util="http://www.springframework.org/schema/util" 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 http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <!-- Quartz common config--> <!-- 總管理類,啟動觸發器的配置, 如果將lazy-init='false'那么容器啟動就會執行調度程序 --> <bean id="startQuartz" lazy-init='false' autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="runSyncHive2OracleJob" /> <ref bean="triggerTestjob" /> </list> </property> <property name="autoStartup" value="true" /> <property name="startupDelay" value="30"/> </bean> <!-- 定時器1: 同步hive數據到oracle --> <!-- 定義執行的對象及對象中的方法 --> <bean id="defineSyncHive2OracleJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="syncHive2OracleComponent" /> <property name="targetMethod" value="execute" /> <property name="concurrent" value="false" /> <!-- 指是否並行執行 --> </bean> <!-- 定義觸發器的時間 --> <bean id="runSyncHive2OracleJob" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail" ref="defineSyncHive2OracleJob" /> <property name="cronExpression"> <value>${crmbi.cronExpression.syncHive2OracleJob}</value> </property> </bean> <!-- 定時器2:測試quartz類的使用方法 --> <!-- 定義調用的對象及對象中的方法 --> <bean id="defTestJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="testJobComponent" /> <property name="targetMethod" value="execute" /> <property name="concurrent" value="false" /> <!-- 是否支持並發 --> </bean> <!-- 觸發器:定義出發器執行的腳本的時間 --> <bean id="triggerTestJob" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail" ref="defTestJob" /> <property name="cronExpression"> <value>${crmbi.cronExpression.testJob}</value> </property> </bean> </beans>
3. 定義執行任務的時間配置文件config.properties.
注意這里的crmbi.cronExpression.isDotestJob用來控制是否執行任務的開關
# 3:00 every day
crmbi.cronExpression.syncHive2OracleJob=0 0 3 * * ?
crmbi.cronExpression.isDoSyncHive2Oracle=true
# each 5 minuts
crmbi.cronExpression.testJob=0 0/5 * * * ?
crmbi.cronExpression.isDoTestJob=true
4. 在攔截器中添加要掃描的包,這里加入了com.crm.scheduler包和config.properties文件的掃描。
<!----這個applicationContext-dao.xml文件中----> <context:component-scan base-package="com.crm.dao"/> <context:component-scan base-package="com.crm.scheduler"/> <context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/> <context:property-placeholder location="classpath:config.properties" ignore-unresolvable="true" />
5.將quartz的配置文件引入到spring容器中。
<?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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 數據訪問層配置 --> <import resource="classpath:spring/applicationContext-dao.xml" /> <!--服務層配置 --> <import resource="classpath:spring/applicationContext-service.xml" /> <!-- 定時任務配置文件 --> <import resource="classpath:spring/applicationContext-quartz.xml" /> </beans>
6. 最后啟動tomcat, 等待一段時間后,可以看到控制台輸出如下:
[BI-CONSOLE] 2016-08-11 18:03:44.939 INFO RequestMappingHandlerMapping.registerHandlerMethod(197) | Mapped "{[/user/showUser],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.crm.action.system.UserController.showUser(org.springframework.ui.Model,java.lang.String,java.lang.String) [BI-CONSOLE] 2016-08-11 18:03:44.940 INFO RequestMappingHandlerMapping.registerHandlerMethod(197) | Mapped "{[/user/updateUserPwd],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.util.Map<java.lang.String, java.lang.Object> com.crm.action.system.UserController.updateUserPwd(java.lang.String,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) [BI-CONSOLE] 2016-08-11 18:03:44.940 INFO RequestMappingHandlerMapping.registerHandlerMethod(197) | Mapped "{[/user/userSave],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.util.Map<java.lang.String, java.lang.Object> com.crm.action.system.UserController.saveUser(org.springframework.ui.Model,com.crm.entity.system.MUser) [BI-CONSOLE] 2016-08-11 18:03:45.533 INFO SimpleUrlHandlerMapping.registerHandler(302) | Root mapping to handler of type [class org.springframework.web.servlet.mvc.ParameterizableViewController] [BI-CONSOLE] 2016-08-11 18:03:45.540 INFO SimpleUrlHandlerMapping.registerHandler(315) | Mapped URL path [/**] onto handler 'org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#0' [BI-CONSOLE] 2016-08-11 18:03:45.581 INFO SimpleUrlHandlerMapping.registerHandler(315) | Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0' [BI-CONSOLE] 2016-08-11 18:03:45.863 INFO DispatcherServlet.initServletBean(498) | FrameworkServlet 'crmbi': initialization completed in 1255 ms 八月 11, 2016 6:03:45 下午 org.apache.coyote.AbstractProtocol start 信息: Starting ProtocolHandler ["http-bio-8080"] 八月 11, 2016 6:03:45 下午 org.apache.coyote.AbstractProtocol start 信息: Starting ProtocolHandler ["ajp-bio-8009"] 八月 11, 2016 6:03:45 下午 org.apache.catalina.startup.Catalina start 信息: Server startup in 14949 ms [BI-CONSOLE] 2016-08-11 18:04:14.583 INFO SchedulerFactoryBean.run(667) | Starting Quartz Scheduler now, after delay of 30 seconds [BI-CONSOLE] 2016-08-11 18:04:14.584 INFO QuartzScheduler.start(575) | Scheduler startQuartz_$_NON_CLUSTERED started. 我是定時任務類,現在的執行時間是2016-08-11 18:05:00
我是定時任務類,現在的執行時間是2016-08-11 18:10:00
7. 附上項目的文檔結構圖如下: