spring 使用註解來調度定時任務

1.在需要加載spring的配置文件裏spring.xml / applicationContext.xml 添加

[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. xmlns:task="http://www.springframework.org/schema/task"  
  2. xsi:schemaLocation="  
  3. http://www.springframework.org/schema/task          
  4. http://www.springframework.org/schema/task/spring-task-3.0.xsd  

2.配置自動調度的包和定時開關

[html] view plaincopy在CODE上查看代碼片派生到我的代碼片

  1. <!-- 使用註解 -->
  2. <context:annotation-config />  
  3. <!-- 自動調度需要掃描的包 -->  
  4.     <context:component-scan base-package="*" />   
  5.     <task:executor id="executor" pool-size="5" />      
  6.     <task:scheduler id="scheduler" pool-size="10" />    
  7.     <task:annotation-driven executor="executor" scheduler="scheduler" />  

3.配置調度和註解調度

[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <!-- 配置調度 需要在類名前添加 @Service -->  
  2.     <!--    
  3.         <task:scheduled-tasks>  
  4.             <task:scheduled ref="demoTask" method="myTestWork" cron="0/10 * * * * ?"/>  
  5.         </task:scheduled-tasks>  
  6.     -->  
  7.     <!-- 不通過配置調度,需要在類名前 @Component/@Service,在方法名 前添加@Scheduled(cron="0/5 * * * * ? ")-->  

4.在web.xml配置裏添加啓動時要掃描的配置文件和監聽

[html] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. <context-param>  
  2.    <param-name>contextConfigLocation</param-name>  
  3.    <param-value>/WEB-INF/applicationContext*.xml</param-value>  
  4.  </context-param>  
  5.  <listener>  
  6.    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  7.  </listener>  

5.添加調度的包

6.類測試

[java] view plaincopy在CODE上查看代碼片派生到我的代碼片
  1. @Service  
  2. public class demo {  
  3.     @Scheduled(cron="0/5 * * * * ? ")  
  4.     public void myTestWork(){  
  5.           
  6.         System.out.println("ssss");  
  7.     }  
  8.   
  9. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章