侧边栏壁纸
博主头像
Epoch

Java开发、Python爬虫、微服务、分布式、前端

  • 累计撰写 93 篇文章
  • 累计创建 110 个标签
  • 累计收到 8 条评论

目 录CONTENT

文章目录

Spring Boot简单定时任务

Epoch
2020-05-18 / 0 评论 / 0 点赞 / 293 阅读 / 700 字 / 正在检测是否收录...

目标:实现springboot的简单的定时任务
工具:IDEA–2020.1
学习目标:实现springboot的简单的定时任务
本次学习的工程下载链接放到文本最后面

  • 首先创建一个springboot项目
    先在启动类上打上注解@EnableScheduling
     package com.xmaven;
     
     import org.springframework.boot.SpringApplication; import
     org.springframework.boot.autoconfigure.SpringBootApplication; import
     org.springframework.scheduling.annotation.EnableScheduling;
     
     @SpringBootApplication //添加 @EnableScheduling 注解,开启对定时任务的支持
     @EnableScheduling 
     public class SpringbootScheduledApplication {
     
         public static void main(String[] args) {
             SpringApplication.run(SpringbootScheduledApplication.class, args);
         }
     
     }
  • 创建一个简单的任务类:
    package com.xmaven.task;
    
    import org.springframework.scheduling.annotation.Scheduled;
    import org.springframework.stereotype.Component;
    
    import java.time.LocalDateTime;
    
    @Component
    public class ScheduledTask {
    
        @Scheduled(fixedRate = 3000)
        public void scheduledTask(){
            System.out.println("任务执行时间:" + LocalDateTime.now());
        }
    }
  • 演示结果如下:
    )VZZA()O0JF_XT3MF074SLU.png

  • @Scheduled详解

  • @Scheduled(fixedRate = 3000) :上一次开始执行时间点之后 3 秒再执行(fixedRate属性:定时任务开始后再次执行定时任务的延时(需等待上次定时任务完成),单位毫秒)

  • @Scheduled(fixedDelay =3000) :上一次执行完毕时间点之后 3 秒再执行(fixedDelay属性:定时任务执行完成后再次执行定时任务的延时(需等待上次定时任务完成),单位毫秒)

  • @Scheduled(initialDelay=1000, fixedRate = 3000) :第一次延迟1秒后执行,之后按fixedRate的规则每3秒执行一次(initialDelay 属性:第一次执行定时任务的延迟时间,需配合fixedDelay或者fixedRate来使用)

  • @Scheduled(cron=“0 0 2 1 * ? *”) :通过cron表达式定义规则

其中,常用的cron表达式有:

0 0 2 1 * ? * :表示在每月 1 日的凌晨 2 点执行
0 15 10 ? * MON-FRI :表示周一到周五每天上午 10:15 执行
0 15 10 ? 6L 2019-2020 :表示 2019-2020 年的每个月的最后一个星期五上午 10:15 执行
0 0 10,14,16 * * ? :每天上午 10 点,下午 2 点,4 点执行
0 0/30 9-17 * * ? :朝九晚五工作时间内每半小时执行
0 0 12 ? * WED :表示每个星期三中午 12 点执行
0 0 12 * * ? :每天中午 12点执行
0 15 10 ? * * :每天上午 10:15 执行
0 15 10 * * ? :每天上午 10:15 执行
0 15 10 * * ? * :每天上午 10:15 执行
0 15 10 * * ? 2019 :2019 年的每天上午 10:15 执行
  • 总结

    主程序入口 @EnableScheduling 开启定时任务
    定时方法上 @Scheduled 设置定时
    cron属性:按cron规则执行
    fixedRate 属性:以固定速率执行
    fixedDelay 属性:上次执行完毕后延迟再执行
    initialDelay 属性:第一次延时执行,第一次执行完毕后延迟后再次执行


下载链接:springboot-scheduled.rar

0

评论区