使用SpringBoot创建定时任务主要有三种创建方式:
1.基于注解(@Scheduled)
2.基于接口(SchedulingConfigurer)实际使用中我们往往想从数据库中读取指定时间来动态执行定时任务,这时候基于接口的定时任务就派上用场了。
3.基于注解设定多线程定时任务
本篇只介绍基于注解开启定时任务
4.1新建定时任务
在SpringBoot第三篇:整合MyBatis-Plus基础上新建一个Task包,在Task新建SaticScheduleTask
package com.firstwave.sfspringboot.Task;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.Scheduled;import java.time.LocalDateTime;/** * @Author: shafei * @Date: 2020-05-21 10:24 * @Version: V1.0 * @Description: */@Configuration //标记配置类,兼备Component的效果。@EnableScheduling //开启定时任务public class SaticScheduleTask { //添加定时任务 @Scheduled(cron = "0/5 * * * * ?")