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 }
  • 相关阅读:
    创建Hive/hbase相关联的表异常
    CDH5.2+CM5.2+impala2+Spark1.1 集群搭建基础环境准备
    【JavaWeb】(10)微信公众号开发进阶
    Ambari-stack介绍
    OSGi中的ServletContext
    笔试面试1 用C实现C库函数itoa, atoi
    SGU 114. Telecasting station 三分or找中位数
    face++实现人脸识别
    磁盘接口与磁盘扫描
    CSDN开源夏令营 百度数据可视化实践 ECharts(4)
  • 原文地址:https://www.cnblogs.com/laoxia/p/9847892.html
Copyright © 2011-2022 走看看