springboot中创建定时任务主要有两种方式:1.基于注解(@Scheduled);2.基于接口(SchedulingConfigurer)。方式1适用于静态定时任务,方式二适用于动态定时任务(即定时时间是可以配置的)。
一、静态定时任务
基于注解(@Scheduled)实现,代码如下:
//注入容器
@Component
//开启定时任务
@EnableScheduling
public class Scheduler {
@Scheduled(cron = "0/5 * * * * ?")
private void testTask(){
System.out.println("执行定时任务!"+ LocalDateTime.now());
}
}
静态定时任务很方便,但是存在缺陷,当我们需要调整执行周期的时候,需要重启应用才能生效,这样对于不能停止的业务不太方便。为了达到实时生效的效果,可以采用接口方式来实现定时任务。
2.动态定时任务
基于接口类SchedulingConfigurer实现,