如何在 Spring Boot 中启用定时任务

添加 @EnableScheduling 注解

可以添加在 Application 类上

java 复制代码
@SpringBootApplication
@EnableScheduling
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

定义定时任务类和方法

定时任务类要注册为Spring IoC 容器的 Bean,或者通过 @Bean 将某个方法的返回值(返回值为定时任务类对象)注册为 Spring IoC 的Bean。

java 复制代码
package com.cmcc.nlpt.sitemessage.task;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class ScheduledTask {

    /**
     * 每日0点执行
     */
    @Scheduled (cron = "0 0 0 * * ?")
    public void doCronTask() {

    }

    /**
     * 本次任务结束到下次任务开始的时间间隔为5秒
     */
    @Scheduled (fixedDelay = 5000)
    public void doFixedDelayTask() {

    }

    /**
     * 两次任务开始时间间间隔为5秒
     */
    @Scheduled(fixedRate = 5000)
    public void doFixedRateTask() {

    }

    /**
     * 第一次任务启动延时1秒,后续任务结束到下次任务开始的时间间隔为5秒
     */
    @Scheduled(initialDelay = 1000, fixedDelay = 5000)
    public void doInitialDelayTask() {

    }
}

通过配置项控制定时任务是否开启

方法一 @ConditionalOnProperty

此方法是控制任务类是否注册为 Spring IoC 的 Bean,可以控制上述所有类型的定时任务是否注册。

yaml 复制代码
# enabled 配置为 false 时定时任务就不会开启
scheduled-task:
  enabled: true
java 复制代码
@Component
@ConditionalOnProperty(name = "scheduled-task.enabled", havingValue = "true")
public class ScheduledTask {
    /**
     * 每日0点执行
     */
    @Scheduled (cron = "0 0 0 * * ?")
    public void doCronTask() {

    }

    /**
     * 本次任务结束到下次任务开始的时间间隔为5秒
     */
    @Scheduled (fixedDelay = 5000)
    public void doFixedDelayTask() {

    }

    /**
     * 两次任务开始时间间间隔为5秒
     */
    @Scheduled(fixedRate = 5000)
    public void doFixedRateTask() {

    }

    /**
     * 第一次任务启动延时1秒,后续任务结束到下次任务开始的时间间隔为5秒
     */
    @Scheduled(initialDelay = 1000, fixedDelay = 5000)
    public void doInitialDelayTask() {

    }
}

方法二 Boolean 标志位

使用此方法定时任务还是会被调度执行,只是在任务执行时什么都不做,也可以控制上述所有类型的定时任务。

yaml 复制代码
scheduled-task:
  enabled: true
java 复制代码
@Component
@ConditionalOnProperty(name = "scheduled-task.enabled", havingValue = "true")
public class ScheduledTask {

    @Value("${scheduled-task.enabled}")
    private Boolean taskEnabled;

    @Scheduled (fixedDelay = 5000)
    public void doFixedDelayTask() {
        if (!taskEnabled) {
            return;
        }
        System.out.println("start to doFixedDelayTask");
    }
}

使用"-"使 cron 定时任务关闭

此方法只适用于 cron 类型的定时任务,不适用于其它类型的定时任务。

注意:yml 文件中配置 - 时要加上双引号或单引号,否则会报错。


关闭 cron 定时任务的配置:

yaml 复制代码
scheduled-task:
  cron: "-"

开始 cron 定时任务的配置,将 cron 表达式配置上即可:

yaml 复制代码
scheduled-task:
  cron: 0 0 0 * * ?
java 复制代码
@Component
public class ScheduledTask {
    /**
     * 每日0点执行
     */
    @Scheduled (cron = "${scheduled-task.cron}")
    public void doCronTask() {

    }
}

参考

相关推荐
小蒜学长37 分钟前
springboot餐厅信息管理系统设计(代码+数据库+LW)
java·数据库·spring boot·后端
Jabes.yang1 小时前
Java大厂面试实录:从Spring Boot到微服务的技术探讨
java·spring boot·spring cloud·微服务·技术面试
咖啡Beans2 小时前
SpringBoot集成MongoDB使用
spring boot·mongodb
q_19132846953 小时前
基于RuoYi框架+Mysql的汽车进销存后台管理系统
数据库·vue.js·spring boot·mysql·汽车·个人开发·若依
悟能不能悟3 小时前
springboot在DTO使用service,怎么写
java·数据库·spring boot
__XYZ3 小时前
RedisTemplate 实现分布式锁
java·spring boot·redis·分布式·junit
Cc00108524 小时前
【AI学习笔记】用AI生成spring boot + redis
spring boot·笔记·学习·ai编程
thginWalker5 小时前
使用Spring Boot构建Web服务层
spring boot
摇滚侠5 小时前
Spring Boot 3零基础教程,Spring Boot 特性介绍,笔记02
java·spring boot·笔记
ahauedu6 小时前
Spring Boot 2.7+ 中 RedisConnectionFactory Autowire 警告的深度解析
java·spring boot·后端