一、定时任务概述

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 注解

  1. @Configuration
  2. @EnableScheduling
  3. public class SpringTaskConfig {
  4. }

或者在入口文件中加入@EnableScheduling 注解

  1. @SpringBootApplication
  2. @EnableScheduling
  3. public class CrontabApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(CrontabApplication.class, args);
  6. }
  7. }

三、实现方式一:cron

  1. @Component
  2. public class Schedule1 {
  3. private int count=0;
  4. @Scheduled(cron="*/6 * * * * ?")
  5. private void process(){
  6. System.out.println("this is scheduler task runing "+(count++));
  7. }
  8. }

四、实现方式二:fixedRate

  1. @Component
  2. public class Schedule2 {
  3. private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
  4. @Scheduled(fixedRate = 6000)
  5. public void reportCurrentTime() {
  6. System.out.println("现在时间:" + dateFormat.format(new Date()));
  7. }
  8. }

fixedRate 指定了间隔时长, 这里是6000ms, 即6s执行一次reportCurrentTime方法

示例:

  • @Scheduled(fixedRate = 6000) 上一次开始执行时间点之后6秒再执行
  • @Scheduled(fixedDelay = 6000) 上一次执行完毕时间点之后6秒再执行
  • @Scheduled(initialDelay=1000, fixedRate=6000) 第一次延迟1秒后执行,之后按fixedRate的规则每6秒执行一次

运行结果:

  1. this is scheduler task runing 0
  2. 现在时间:11:32:27
  3. this is scheduler task runing 1
  4. 现在时间:11:32:33
  5. this is scheduler task runing 2
  6. 现在时间:11:32:39
  7. this is scheduler task runing 3
  8. 现在时间:11:32:45
  9. this is scheduler task runing 4
  10. 现在时间:11:32:51
  11. this is scheduler task runing 5
  12. 现在时间:11:32:57