美文网首页
springboot @Scheduled创建定时任务七

springboot @Scheduled创建定时任务七

作者: AmeeLove | 来源:发表于2018-04-25 12:28 被阅读80次

    创建定时任务

    在Spring Boot的主类中加入@EnableScheduling注解,启用定时任务的配置

    
    @SpringBootApplication
    @EnableScheduling
    public class Chapter02Application {
    
        public static  void main(String [] args){
            SpringApplication.run(Chapter02Application.class, args);
    
        }
    }
    
    
    image.png

    创建定时任务实现类

    @Component
    public class ScheduledTasks {
    
        private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    
        @Scheduled(fixedRate = 5000)
        public void reportCurrentTime() {
            System.out.println("reportCurrentTime 现在时间:" + dateFormat.format(new Date()));
        }
    
        @Scheduled(fixedDelay=8000)
        public void delayCurrentTime() {
            System.out.println("delayCurrentTime 现在时间: " + dateFormat.format(new Date()));
        }
    
    
        @Scheduled(cron = "*/10 * * * * ?")
        public void cronCurrentTime() {
            System.out.println("cronCurrentTime 现在时间  :" + dateFormat.format(new Date()));
        }
    }
    
    
    image.png
    cronCurrentTime 现在时间  :12:26:10
    reportCurrentTime 现在时间:12:26:10
    delayCurrentTime 现在时间: 12:26:13
    reportCurrentTime 现在时间:12:26:15
    cronCurrentTime 现在时间  :12:26:20
    reportCurrentTime 现在时间:12:26:20
    delayCurrentTime 现在时间: 12:26:21
    reportCurrentTime 现在时间:12:26:25
    delayCurrentTime 现在时间: 12:26:29
    cronCurrentTime 现在时间  :12:26:30
    reportCurrentTime 现在时间:12:26:30
    
    • @Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行
    • @Scheduled(fixedDelay = 8000) :上一次执行完毕时间点之后8秒再执行
      @Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
    • @Scheduled(cron="*/10 * * * * *") :通过cron表达式定义规则

    相关文章

      网友评论

          本文标题:springboot @Scheduled创建定时任务七

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