美文网首页
springboot cron定时任务配置

springboot cron定时任务配置

作者: hirolin | 来源:发表于2019-04-24 22:25 被阅读0次

    前一篇文章记录springboot配置mybatis。在基础上增加cron定时任务配置。

    • 开启定时任务
    • 任务代码实现
    开启定时任务

    开启定时任务比较简单,在入口出打开 @EnableScheduling

    @SpringBootApplication
    @MapperScan("com.hiro.demo.db")
    @EnableScheduling
    public class DemoApplication {
        public static void main(String [] args) {
            SpringApplication.run(DemoApplication.class,args);
        }
    }
    
    任务代码实现
    package com.hiro.demo.timer;
    
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    /**
     * Project: springbootDemo
     *
     * @author : hirolin
     * @date : 2019/3/25 22:44
     */
    @Component
    public class MainTimer {
    
        @Scheduled(cron = "${demo.backend.timer}")
        public void backendTimer(){
            System.out.println("test");
        }
    }
    

    其中 cron="${demo.backend.timer}" 是配置在application.yml中:

    #定时任务执行
    demo:
      backend:
          timer: "*/1 * * * * *"
    

    项目运行后可看到控制台每秒打印:


    ```shell

    cron常用
    * * * * * * *
    1 秒(0~59)
    2 分钟(0~59)
    3 小时(0~23)
    4 天(0~31)
    5 月(0~11)
    6 星期(1~7 1=SUN 或 SUN,MON,TUE,WED,THU,FRI,SAT)
    7.年份(1970-2099)
    例如每秒钟:
    " */1 * * * * *"
    每天中午12点:
    “0 0 12 * * ? " 每天中午12点触发

    相关文章

      网友评论

          本文标题:springboot cron定时任务配置

          本文链接:https://www.haomeiwen.com/subject/nvxogqtx.html