spring 使用注解来调度定时任务

来源:互联网 发布:预结算软件 编辑:程序博客网 时间:2024/05/01 03:49

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:component-scan base-package="*" />   
  3.     <task:executor id="executor" pool-size="5" />      
  4.     <task:scheduler id="scheduler" pool-size="10" />    
  5.     <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. }  
1 0
原创粉丝点击