一、定时任务概述
SpringTask是Spring自主研发的轻量级定时任务工具,相比于Quartz更加简单方便,且不需要引入其他依赖即可使用。
SpringBoot 默认已经帮我们实现了定时任务,只需要添加相应的注解就可以实现
二、Cron表达式
Cron表达式是一个字符串,包括6~7个时间元素,在SpringTask中可以用于指定任务的执行时间。
Cron的语法格式
时间元素 | 可出现的字符 | 有效数值范围 |
---|---|---|
Seconds | , - * / | 0-59 |
Minutes | , - * / | 0-59 |
Hours | , - * / | 0-23 |
DayofMonth | , - * / ? L W | 0-31 |
Month | , - * / | 1-12 |
DayofWeek | , - * / ? L # | 1-7或SUN-SAT |
Cron格式中特殊字符说明
字符 | 作用 | 举例 |
---|---|---|
, | 列出枚举值 | 在Minutes域使用5,10,表示在5分和10分各触发一次 |
- | 表示触发范围 | 在Minutes域使用5-10,表示从5分到10分钟每分钟触发一次 |
* | 匹配任意值 | 在Minutes域使用*, 表示每分钟都会触发一次 |
/ | 起始时间开始触发,每隔固定时间触发一次 | 在Minutes域使用5/10,表示5分时触发一次,每10分钟再触发一次 |
? | 在DayofMonth和DayofWeek中,用于匹配任意值 | 在DayofMonth域使用?,表示每天都触发一次 |
# | 在DayofMonth中,确定第几个星期几 | 1#3表示第三个星期日 |
L | 表示最后 | 在DayofWeek中使用5L,表示在最后一个星期四触发 |
W | 表示有效工作日(周一到周五) | 在DayofMonth使用5W,如果5日是星期六,则将在最近的工作日4日触发一次 |
cron 可以使用在线Cron表达式生成器生成
三、@EnableScheduling
要使定时任务起效,首先添加一个定时任务配置类SpringTaskConfig
,并添加 @EnableScheduling
注解
@Configuration
@EnableScheduling
public class SpringTaskConfig {
}
或者在入口文件中加入@EnableScheduling
注解
@SpringBootApplication
@EnableScheduling
public class CrontabApplication {
public static void main(String[] args) {
SpringApplication.run(CrontabApplication.class, args);
}
}
三、实现方式一:cron
@Component
public class Schedule1 {
private int count=0;
@Scheduled(cron="*/6 * * * * ?")
private void process(){
System.out.println("this is scheduler task runing "+(count++));
}
}
四、实现方式二:fixedRate
@Component
public class Schedule2 {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 6000)
public void reportCurrentTime() {
System.out.println("现在时间:" + dateFormat.format(new Date()));
}
}
fixedRate 指定了间隔时长, 这里是6000ms, 即6s执行一次reportCurrentTime方法
示例:
@Scheduled(fixedRate = 6000)
上一次开始执行时间点之后6秒再执行@Scheduled(fixedDelay = 6000)
上一次执行完毕时间点之后6秒再执行@Scheduled(initialDelay=1000, fixedRate=6000)
第一次延迟1秒后执行,之后按fixedRate的规则每6秒执行一次
运行结果:
this is scheduler task runing 0
现在时间:11:32:27
this is scheduler task runing 1
现在时间:11:32:33
this is scheduler task runing 2
现在时间:11:32:39
this is scheduler task runing 3
现在时间:11:32:45
this is scheduler task runing 4
现在时间:11:32:51
this is scheduler task runing 5
现在时间:11:32:57