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秒执行一次

  • 相关阅读:
    ios-app提交审核问题总结
    mui混合app请求过程处理(缓存、加载、刷新机制)
    vue引入assets和static静态资源问题
    mui入门教程
    scroll.js
    jQuery.Running.js
    CSS 编码技巧
    textillate.js
    3. 戏说VHDL之入门游戏一:流水灯
    2. 流水灯小计
  • 原文地址:https://www.cnblogs.com/geniushuangxiao/p/6706719.html
Copyright © 2011-2022 走看看