如何在 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() {

    }
}

参考

相关推荐
爱吃烤鸡翅的酸菜鱼3 小时前
【Spring】原理解析:Spring Boot 自动配置
java·spring boot
十八旬3 小时前
苍穹外卖项目实战(day7-1)-缓存菜品和缓存套餐功能-记录实战教程、问题的解决方法以及完整代码
java·数据库·spring boot·redis·缓存·spring cache
郑洁文4 小时前
基于SpringBoot的天气预报系统的设计与实现
java·spring boot·后端·毕设
optimistic_chen4 小时前
【Java EE进阶 --- SpringBoot】Spring DI详解
spring boot·笔记·后端·spring·java-ee·mvc·di
中国胖子风清扬5 小时前
Rust 日志库完全指南:从入门到精通
spring boot·后端·rust·学习方法·logback
xiaogg36786 小时前
springboot rabbitmq 延时队列消息确认收货订单已完成
spring boot·rabbitmq·java-rabbitmq
麦兜*6 小时前
MongoDB 6.0 新特性解读:时间序列集合与加密查询
数据库·spring boot·mongodb·spring·spring cloud·系统架构
依稀i1236 小时前
Spring Boot + MySQL 创建超级管理员
spring boot·mysql
千里码aicood6 小时前
【springboot+vue】党员党建活动管理平台(源码+文档+调试+基础修改+答疑)
java·数据库·spring boot
Chan166 小时前
【智能协同云图库】基于统一接口架构构建多维度分析功能、结合 ECharts 可视化与权限校验实现用户 / 管理员图库统计、通过 SQL 优化与流式处理提升数据
java·spring boot·后端·sql·spring·intellij-idea·echarts