javascript
Spring Shedule Task之注解实现 (两次启动Schedule Task 的解决方案)
在spring 中的新引入的task?命名空間。可以部分取代?quartz 功能,配置和API更加簡單,并且支持注解方式。
?
第一步:
??????? 在Spring的相關配置文件中(applicationContext.xml或者是{project_name}_servelt.xml或者是獨立的配置文件如XXX_quartz.xml)中配置并開啟Spring Schedule Task.注意其中高亮的部分是必須的。
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:aop="http://www.springframework.org/schema/aop" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xmlns:context="http://www.springframework.org/schema/context" 7 xmlns:mvc="http://www.springframework.org/schema/mvc" 8 xmlns:p="http://www.springframework.org/schema/p" 9 xmlns:task="http://www.springframework.org/schema/task" 10 xsi:schemaLocation=" 11 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 12 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 13 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd 14 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 15 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd 16 http://www.springframework.org/schema/task 17 http://www.springframework.org/schema/task/spring-task-3.0.xsd 18 "> 19 <mvc:annotation-driven /> 20 <context:component-scan base-package="com.mytools.validator.engine" /> 21 22 <!-- 啟動定時器 --> 23 <task:annotation-driven/> 24 </beans>?
?
?
第二步:
??????? 可以在類中的需要定時執行的方法下指定如下Annotation
1 @Scheduled(cron="0 33/3 * * * ?") //每小時的33分鐘開始執行,每3分鐘執行1次 2 public void start() throws ServletException { 3 validate(); 4 }?
備注:其實@Scheduled中可以指定如下3種時間表達式:
(1)fixedRate:每隔多少毫秒執行一次該方法。如:
1 @Scheduled(fixedRate=2000) // 每隔2秒執行一次 2 public void scheduleMethod(){ 3 System.out.println("Hello world..."); 4 }?
(2)fixedDelay:當一次方法執行完畢之后,延遲多少毫秒再執行該方法。
(3)cron:詳細配置了該方法在什么時候執行。cron值是一個cron表達式。如:
?
1 @Scheduled(cron="0 0 0 * * SAT") 2 public voidarchiveOldSpittles() { 3 // ... 4 }?
?到指定時間后,任務總是執行2次的解決方案:
這是因為我們很容易在一個基于Spring的Web工程中啟動2個定時線程:
第一次:web容器啟動的時候,讀取applicationContext.xml(或者別的Spring核心配置文件)文件時,會加載一次。
第二次:Spring本身會加載applicationContext.xml(或者別的Spring核心配置文件)一次。
解決方案:將你的Task的相關配置獨立出來并在web.xml中通過context-param加載。而不是通過spring加載。
1) 獨立出Spring-Task,如新命名一個文件名叫cms_quartz.xml
2)??? 在web.xml中去加載該文件:
1 <context-param> 2 <param-name>contextConfigLocation</param-name> 3 <param-value>/WEB-INF/cms-servlet.xml, classpath:cms-quartz.xml</param-value> 4 </context-param>?
注:出自 http://www.tuicool.com/articles/jmU7bq
?
轉載于:https://www.cnblogs.com/kzhan/p/5742523.html
總結
以上是生活随笔為你收集整理的Spring Shedule Task之注解实现 (两次启动Schedule Task 的解决方案)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Nginx 配置从零开始
- 下一篇: JS——无缝滚动