在 Spring + SpringMVC 环境中,一般来说,要实现定时任务,我们有两中方案,一种是使用 Spring 自带的定时任务处理器 @Scheduled 注解,另一种就是使用第三方框架 Quartz ,Spring Boot 源自 Spring+SpringMVC ,因此天然具备这两个 Spring 中的定时任务实现策略,当然也支持 Quartz,本文我们就来看下 Spring Boot 中两种定时任务的实现方式。
一、@Scheduled
使用 @Scheduled 非常容易,直接创建一个 Spring Boot 项目,并且添加 web 依赖 spring-boot-starter-web,项目创建成功后,在启动类上面加上添加 @EnableScheduling 注解,开启定时任务:
@SpringBootApplication
@EnableScheduling
public class ScheduledApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduledApplication.class, args);
}
}
配置定时任务:
@Component
public class ScheduledTask {
@Scheduled(fixedRate = 6000)
public void task(){
System.out.println(new Date()+"定时任务task触发了");
}
@Scheduled(cron = "30 * * * * ?") //每分钟的30秒触发
public void task1(){
System.out.println(new Date()+":定时任务task1触发了");
}
}
1、首先使用 @Scheduled 注解开启一个定时任务。
2、fixedRate 表示任务执行之间的时间间隔,具体是指两次任务的开始时间间隔,即第二次任务开始时,第一次任务可能还没结束。
3、fixedDelay 表示任务执行之间的时间间隔,具体是指本次任务结束到下次任务开始之间的时间间隔。
4、initialDelay 表示首次任务启动的延迟时间。
5、所有时间的单位都是毫秒。
6、上面这是一个基本用法,除了这几个基本属性之外,@Scheduled 注解也支持 cron 表达式,使用 cron 表达式,可以非常丰富的描述定时任务的时间。cron 表达式格式如下:
cron表达式格式:
{
秒数} {
分钟} {
小时