zoukankan      html  css  js  c++  java
  • Spring定时任务

    一、实现方法1

    1、web.xml引入task命名空间:

    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、Spring配置文件添加扫描包注解: 

    <context:component-scan base-package="cn.hncu">
    </context:component-scan>

    3、定时任务扫描注解

        <!-- S 配置定时任务-->
        <task:executor id="executor" pool-size="5" />
        <!--配置线程池-->
        <task:scheduler id="scheduler" pool-size="10" />
        <task:annotation-driven executor="executor" scheduler="scheduler" />
        <!--E 配置定时任务-->

    4、代码实现: 

     1 @Component
     2 public class DemoTask {
     3     @Scheduled(fixedRate  = 5000)
     4     //以一个固定延迟时间5秒钟调用一次执行
     5     public void demo2(){
     6         logger.info("定时任务demo2开始.");
     7         long begin = System.currentTimeMillis();
     8         //执行你需要操作的定时任务
     9         try {
    10             Thread.sleep(1000);
    11         } catch (InterruptedException e) {
    12             e.printStackTrace();
    13         }
    14         long end = System.currentTimeMillis();
    15         logger.info("定时任务demo2结束,共耗时:[" + (end-begin)+ "]毫秒");
    16     }
    17 }

    二、实现方法2:

    1、方法1中的第一步和第三步可以去掉;

    2、代码实现:

     1 @EnableScheduling
     2 @Component
     3 @Lazy(false)
     4 public class DemoTask {
     5     @Scheduled(cron = "*/5 * * * * ?")
     6     //以一个固定延迟时间5秒钟调用一次执行
     7     public void demo2(){
     8         logger.info("定时任务demo2开始.");
     9         long begin = System.currentTimeMillis();
    10         //执行你需要操作的定时任务
    11         try {
    12             Thread.sleep(1000);
    13         } catch (InterruptedException e) {
    14             e.printStackTrace();
    15         }
    16         long end = System.currentTimeMillis();
    17         logger.info("定时任务demo2结束,共耗时:[" + (end-begin)+ "]毫秒");
    18     }
    19 }
  • 相关阅读:
    基于WPF的UI自动化测试[1] 自动化测试工具
    PSR
    技术型人员如何晋升项目经理
    HyperV 组件架构(1)—总体架构
    从技术到管理:工作转型后角色定位
    Web性能优化方案
    一个项目经理的一些个人体会
    从技术人才到项目管理的跨越
    研发项目经理的管理
    从程序类转向销售类工作,该如何进行?
  • 原文地址:https://www.cnblogs.com/laoxia/p/9847892.html
Copyright © 2011-2022 走看看