springboot-定时任务

大纲:

  1. springboot如何开启定时任务
  2. 3种定时任务
  3. cron表达式

一、springboot定时任务需要@EnableScheduling注解

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

二、定时任务有三种执行方式,首先每次任务执行要等到上次任务执行完成后才会执行,fixedDelay,fixedRate可以设定初始延迟时间initialDelay,cron表达式不能。

  1. fixedDelay:本次任务执行完成后,延迟xx秒后执行下次任务。
  2. fixedRate:固定xx秒执行一次,但如果执行阻塞时间超过下次执行时间,则任务执行完成后立即执行下一次。
  3. cron表达式:按照表达式执行,但如果执行阻塞时间超过下次执行时间,则跳过下次的表达式执行时间,等待再下一次的执行时间。
@Component
public class DelayJob {

    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

    @Scheduled(fixedDelay=2000)
    public void testFixedDelay(){
        System.out.println("testFixedDelay begin at "+format.format(new Date()));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("testFixedDelay end at"+format.format(new Date()));
    }

    @Scheduled(fixedRate=2000)
    public void testFixedRate(){
        System.out.println("testFixedRate begin at "+format.format(new Date()));
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("testFixedRate end at"+format.format(new Date()));
    }

    @Scheduled(cron="0/4 * * * * ?")
    public void testCronTab(){
        System.out.println("testCronTab begin at "+format.format(new Date()));
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("testCronTab end at"+format.format(new Date()));
    }
}

三、cron表达式共7位

  • 1位:秒(0-59)
  • 2位:分(0-59)
  • 3位:时(0-23)
  • 4位:日(1-31)
  • 5位:月(1-12)
  • 6位:星期(1-7,1表示礼拜天,2表示礼拜1)
  • 7位:年份(可空)

cron表达式特殊符号

  • *:每
  • ?:出现在日和星期位上,这2位互斥,当日上有值,星期位上为?,同理反之
  • -:范围
  • ,:或
  • /:a/b,a是初始值,b是步长

例:

10/20 1 1,4 * 1-3 ?  //1到3月每天,1点和4点的:1分10秒,30秒,50秒执行

10/20:十秒开始每次加20秒

1:1分钟

1,4:1点或4点

*:每天

1-3:1到3月

?:日位有值,星期位为?

原文地址:https://www.cnblogs.com/liuboyuan/p/10342021.html