十三、springboot集成定时任务(Scheduling Tasks)

定时任务(Scheduling Tasks)

在springboot创建定时任务比较简单,只需2步:

  • 1.在程序的入口加上@EnableScheduling注解。
  • 2.在定时方法上加@Scheduled注解。

1、springboot默认已经帮我们实现了定时任务,只需要添加相应的注解就可以实现

  spring-boot-starter

2、启动类启用定时

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

@SpringBootApplication
@EnableDiscoveryClient
@EnableScheduling
public class MyApplication {

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

}

3、创建定时任务实现类

创建一个定时任务,每过5s在控制台打印当前时间。

@Component
public class ScheduledTasks {

    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        log.info("The time is now {}", dateFormat.format(new Date()));
    }
}

4、参数说明

  @Scheduled详解

    通过在方法上加@Scheduled注解,表明该方法是一个调度任务。

    @Scheduled 参数可以接受两种定时的设置,一种是我们常用的cron="*/6 * * * * ?",一种是 fixedRate = 6000,两种都表示每隔六秒打印一下内容

@Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行
@Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行
@Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
@Scheduled(cron="*/5 * * * * *") :通过cron表达式定义规则

参考:Scheduling Tasks

原文地址:https://www.cnblogs.com/soul-wonder/p/9008255.html