Spring Boot 2.X 实现简易定时任务功能


1 摘要

定时任务在项目中的应用相当广泛,比如定时推送消息,定时更新一些数据状态等等,Spring 已经集成定时任务(Spring context 包中),在 Spring Boot 项目中使用起来相当方便,无需再引入第三方 jar。以下为基于 Spring Boot 2.x 实现简易的定时任务功能。

2 Maven 依赖

Spring 3.0 起加入定时任务功能,在 spring context 包中,Spring Boot 项目中 starter-actuator 中已经包含

../pom.xml
../demo-schedule/pom.xml
            <!-- spring boot starter -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
                <version>${springboot.version}</version>
            </dependency>

其中的版本为:

<springboot.version>2.0.6.RELEASE</springboot.version>

3 核心代码

3.1 Spring Boot 启动类

在 Spring Boot 项目启动类上,需要使用 @EnableScheduling 注解以启动定时任务功能

../demo-schedule/src/main/java/com/ljq/demo/springboot/schedule/DemoScheduleApplication.java
package com.ljq.demo.springboot.schedule;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.scheduling.annotation.EnableScheduling;

/**
 * @author junqiang.lu
 */
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class},scanBasePackages = {"com.ljq.demo.springboot.schedule"})
@EnableScheduling
public class DemoScheduleApplication {

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

}

3.2 定时任务类
../demo-schedule/src/main/java/com/ljq/demo/springboot/schedule/cronjob/UserSchedule.java
package com.ljq.demo.springboot.schedule.cronjob;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.support.CronSequenceGenerator;
import org.springframework.stereotype.Component;

/**
 * @Description: 用户模块定时任务
 * @Author: junqiang.lu
 * @Date: 2019/6/14
 */
@Slf4j
@Component
public class UserSchedule {

    /**
     * fixedRate 测试
     * fixedRate: 间隔固定的时间(单位: 毫秒)进行任务执行,无论当前任务是否执行完成,
     *     都不会影响下一次的任务执行;
     *     如果多次任务累计没有执行完成,可能会出现内存溢出的问题(Out of memory exception)
     */
    @Scheduled(fixedRate = 5 * 1000)
    public void fixedRateDemo() {
        log.debug("{}","FixedRate Demo ----------");
    }

    /**
     * fixedDelay 测试
     * fixedDelay: 每次任务执行结束后间隔固定的时间(单位: 毫秒)进行下一次的任务
     */
    @Scheduled(fixedDelay = 5 * 1000)
    public void fixedDelayDemo() throws InterruptedException {
        Thread.sleep(1000);
        log.debug("{}", "FixedDelay Demo ++++++++++");
    }

    /**
     * cron 表达式测试
     * 注意: Spring schedule cron 表达式必须是 6 个字段,而非 7 个字段
     * 没有「年」这一项,如果使用 7 个字段的 cron 表达式,则会报错
     * spring cron 表达式参考: https://riptutorial.com/spring/example/21209/cron-expression
     */
    @Scheduled(cron = "*/5 * * * * ?")
    public void cronDemo() {
        String[] cron = {"*/5 * * * * ?", "*/5 * * * * ? *"};
        boolean cronFlag;
        for (int i = 0; i < cron.length; i++) {
            cronFlag = CronSequenceGenerator.isValidExpression(cron[i]);
            log.debug("cron: {}, cronFlag: {}", cron[i], cronFlag);
        }
        log.debug("{}","Cron Demo .........");
    }

}

4 参考资料推荐

spring 官方文档: Scheduling Tasks

The @Scheduled Annotation in Spring

spring Cron expression

5 注意事项

  • Spring 项目中的 cron 表达式必须为 6 个字段,没有最后的 「年」这一项

6 Github 源码

Gtihub 源码地址 : https://github.com/Flying9001/springBootDemo

个人公众号:404Code,分享半个互联网人的技术与思考,感兴趣的可以关注.
404Code

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值