springBoot内置定时任务

应用场景

业务监控,定时发送邮件,定时删除缓存等等。

Spring Boot 内置定时

pom 包配置

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
</dependencies>

启动类开启定时

在启动类上面加上@EnableScheduling即可开启定时:

@SpringBootApplication
@EnableScheduling
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

创建定时任务实现类

使用 Spring Boot 自带的定时非常的简单,只需要在方法上面添加 @Scheduled 注解即可。设置 process() 每隔六秒执行一次,并统计执行的次数。

[[@Component]()]
public class SchedulerTask {

    private int count = 0;

    @Scheduled(cron="*/6 * * * * ?")
    public void process() {
        System.out.println("this is scheduler task runing  "+(count++));
    }

}

@Component
public class SchedulerTask2 {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    /**
     * @Scheduled(fixedRate = 6000) :上一次开始执行时间点之后 6 秒再执行。
     */
    @Scheduled(fixedRate = 6000)
    public void reportCurrentTime() {
        System.out.println("现在时间:" + dateFormat.format(new Date()));
    }
}

启动项目之后,就会在控制台看到打印的结果,结果如下:

this is scheduler task runing  0
现在时间:09:44:17
this is scheduler task runing  1
现在时间:09:44:23
this is scheduler task runing  2
现在时间:09:44:29
this is scheduler task runing  3
现在时间:09:44:35

说明两个方法都按照固定 6 秒的频率来执行。

参数说明

@Scheduled 参数可以接受两种定时的设置,一种是常用的cron="*/6 * * * * ?",一种是 fixedRate = 6000,两种都可表示固定周期执行定时任务。

fixedRate 说明

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

cron 说明

cron 一共有 7 位,最后一位是年,Spring Boot 定时方案中只需要设置 6 位即可:

- 第一位,表示秒,取值 0-59;
- 第二位,表示分,取值 0-59;
- 第三位,表示小时,取值 0-23;
- 第四位,日期天/日,取值 1-31;
- 第五位,日期月份,取值 1-12;
- 第六位,星期,取值 1-7,星期一、星期二…;
注:不是第1周、第2周的意思,另外:1表示星期天,2表示星期一。
- 第七位,年份,可以留空,取值 1970-2099。

cron 中,还有一些特殊的符号,含义如下:

(*)星号:可以理解为每的意思,每秒、每分、每天、每月、每年……。
(?)问号:问号只能出现在日期和星期这两个位置,表示这个位置的值不确定,每天 3 点执行,所以第六位星期的位置是不需要关注的,就是不确定的值。同时,日期和星期是两个相互排斥的元素,通过问号来表明不指定值。假如 1 月 10 日是星期一,如果在星期的位置是另指定星期二,就前后冲突矛盾了。
(-)减号:表达一个范围,如在小时字段中使用“10-12”,则表示从 10~12 点,即 10、11、12。
(,)逗号:表达一个列表值,如在星期字段中使用“1、2、4”,则表示星期一、星期二、星期四。
(/)斜杠:如 x/y,x 是开始值,y 是步长,比如在第一位(秒) 0/15 就是,从 0 秒开始,每 15 秒,最后就是 0、15、30、45、60,另 */y,等同于 0/y。

下面列举几个常用的例子。

0 0 3 * * ?     每天 3 点执行。
0 5 3 * * ?     每天 3 点 5 分执行。
0 5 3 ? * *     每天 3 点 5 分执行,与上面作用相同。
0 5/10 3 * * ?  每天 3 点的 5 分、15 分、25 分、35 分、45 分、55 分这几个时间点执行。
0 10 3 ? * 1    每周星期天,3点10分 执行,注:1 表示星期天。  
0 10 3 ? * 1#3  每个月的第 三 个星期,星期天执行,# 号只能出现在星期的位置。

以上就是 Spring Boot 自定的定时方案,使用起来非常的简单方便。

结束

如果仅需要执行简单定时任务,就可以使用 Spring Boot 自带 Scheduled,可以非常简单和方便的使用。