您的位置:首页 > 编程语言 > Java开发

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

2015-08-05 13:15 567 查看
1.在需要加载spring的配置文件里spring.xml / applicationContext.xml 添加

[html] view
plaincopy





xmlns:task="http://www.springframework.org/schema/task"  

xsi:schemaLocation="  
http://www.springframework.org/schema/task           http://www.springframework.org/schema/task/spring-task-3.0.xsd  
2.配置自动调度的包和定时开关

[html] view
plaincopy





<!--
使用注解 -->

<context:annotation-config />  

<!-- 自动调度需要扫描的包 -->  

    <context:component-scan base-package="*" />   

    <task:executor id="executor" pool-size="5" />      

    <task:scheduler id="scheduler" pool-size="10" />    

    <task:annotation-driven executor="executor" scheduler="scheduler" />  

3.配置调度和注解调度

[html] view
plaincopy





<!-- 配置调度 需要在类名前添加 @Service -->  

    <!--    

        <task:scheduled-tasks>  

            <task:scheduled ref="demoTask" method="myTestWork" cron="0/10 * * * * ?"/>  

        </task:scheduled-tasks>  

    -->  

    <!-- 不通过配置调度,需要在类名前 @Component/@Service,在方法名 前添加@Scheduled(cron="0/5 * * * * ? ")-->  

4.在web.xml配置里添加启动时要扫描的配置文件和监听

[html] view
plaincopy





<context-param>  

   <param-name>contextConfigLocation</param-name>  

   <param-value>/WEB-INF/applicationContext*.xml</param-value>  

 </context-param>  

 <listener>  

   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  

 </listener>  

5.添加调度的包

6.类测试

[java] view
plaincopy





@Service  

public class demo {  

    @Scheduled(cron="0/5 * * * * ? ")  

    public void myTestWork(){  

          

        System.out.println("ssss");  

    }  

  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: