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

    01、@Scheduled注解参数

      @Scheduled支持fixedRatefixedDelaycron表达式参数。其中,fixedRate和fixedDelay没有区别,都是启动时执行1次,每隔n毫秒执行。cron表达式相对灵活复杂,下文会详细讲述。

    02、POM配置

    <!--继承Spring Boot父工程-->
    <
    parent>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-starter-parent</artifactId>   <version>1.5.6.RELEASE</version> </parent> <dependencies>
      <!--依赖Spring Boot Starter-->   <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter</artifactId>   </dependency> </dependencies>

    03、开启Scheduled功能

    @SpringBootApplication
    @EnableScheduling    //开启Schedule功能
    public class Application {
        public static void main(String[] args) throws Exception {
            SpringApplication.run(Application.class);
        }
    }

    04、Scheduled Tasks Bean

    @Component
    public class ScheduledTasks {
    
        private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
    
        private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    
        @Scheduled(fixedRate = 3000)    //启动时执行,然后每隔3s执行一次
        public void reportCurrentTimeWithFixedRate() {
            log.info("FixedRate:Current Time:{}", dateFormat.format(new Date()));
        }
    
        @Scheduled(fixedDelay = 1000)    //启动时执行,然后每隔1s执行一次
        public void reportCurrentTimeWithFixedDelay() {
            log.info("FixedDelay:Current Time:{}", dateFormat.format(new Date()));
        }
    
        @Scheduled(cron = "*/2 * * * * *")    //启动时不执行,然后每隔2s执行一次
        public void reportCurrentTimeUsingCronExpression() {
            log.info("Cron Expression:Current Time:{}", dateFormat.format(new Date()));
        }
    }

    05、cron表达式详解

      cron表达式由空格分开的6部分组成

      

      例1:星期六和星期天,7月-8月,1 3 5号,每秒钟执行1次

      例2:星期一-星期五,每天9点0分0秒执行1次

      例3:23-7时,每秒执行1次

      例4:从第3秒开始,每2秒执行一次

  • 相关阅读:
    如何在CentOS系统中安装字体 51CTO.COM
    C++检查输入数据类型? 知乎
    义乌市爱因宝母婴用品有限公司_公司简介
    硬盘对拷必备 AGE USB/eSATA对拷机现卖场!_青岛行情中关村在线
    Download: Microsoft SQL Server Management Studio Express Microsoft Download Center Download Details
    今晚看啥
    nano接收器
    12306订票助手 (版本 3.5.0)
    Microsoft® SQL Server® 2008 Management Studio Express
    有线键盘和鼠标确实应该退出历史舞台了
  • 原文地址:https://www.cnblogs.com/geniushuangxiao/p/6706719.html
Copyright © 2011-2022 走看看