Springboot 之 使用Scheduled做定时任务

在定时任务中一般有两种情况:

指定何时执行任务
指定多长时间后执行任务

这两种情况在Springboot中使用Scheduled都比较简单的就能实现了。

1.修改程序入口

@SpringBootApplication
@EnableScheduling
public class RootApplication {

    public static void main(String [] args) {
        SpringApplication.run(RootApplication.class, args);
    }
}

在程序入口的类上加上注释@EnableScheduling即可开启定时任务。

2.编写定时任务类

@Component
public class MyTimer {

    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 3000)
    public void timerRate() {
        System.out.println(sdf.format(new Date()));
    }
}

在程序启动后控制台将每隔3秒输入一次当前时间,如:
23:08:48
23:08:51
23:08:54

注意: 需要在定时任务的类上加上注释:@Component,在具体的定时任务方法上加上注释@Scheduled即可启动该定时任务。

3.@Scheduled中的参数:

  1. @Scheduled(fixedRate=3000):上一次开始执行时间点后3秒再次执行;
  2. @Scheduled(fixedDelay=3000):上一次执行完毕时间点后3秒再次执行;
  3. @Scheduled(initialDelay=1000, fixedDelay=3000):第一次延迟1秒执行,然后在上一次执行完毕时间点后3秒再次执行;
  4. @Scheduled(cron="* * * * * ?"):按cron规则执行。

下面贴出完整的例子:

package com.zslin.timers;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class MyTimer {

    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

    //每3秒执行一次
    @Scheduled(fixedRate = 3000)
    public void timerRate() {
        System.out.println(sdf.format(new Date()));
    }

    //第一次延迟1秒执行,当执行完后3秒再执行
    @Scheduled(initialDelay = 1000, fixedDelay = 3000)
    public void timerInit() {
        System.out.println("init : "+sdf.format(new Date()));
    }

    //每天23点27分50秒时执行
    @Scheduled(cron = "50 27 23 * * ?")
    public void timerCron() {
        System.out.println("current time : "+ sdf.format(new Date()));
    }
}
posted @ 2021-06-29 21:15  叶落无蝉鸣  阅读(305)  评论(0编辑  收藏  举报