【SpringBoot 调度任务】

在 Spring Boot 中实现调度任务(Scheduled Tasks),通过使用 @EnableScheduling 和 @Scheduled 注解来完成。

添加依赖

pom.xml 文件中有以下依赖项:

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>

Spring Boot Starter 已经包含了调度任务所需的所有依赖。

启用调度任务支持

需要在主应用程序类或配置类上添加 @EnableScheduling 注解以启用调度功能。

java 复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

创建调度任务

在你想要定义调度任务的组件类上使用 @Component 或其他合适的组件注解,并在方法上使用 @Scheduled 注解来指定任务执行的时间规则。

java 复制代码
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class MyScheduledTasks {

    // 每5秒执行一次任务
    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println("执行时间:" + System.currentTimeMillis() / 1000);
    }

    // 在每天凌晨1点执行任务
    @Scheduled(cron = "0 0 1 * * ?")
    public void executeDailyTask() {
        System.out.println("每日凌晨1点执行的任务");
    }
}

@Scheduled 注解可以接受几种不同的参数:

  • cron: 使用标准的 cron 表达式来定义复杂的调度模式。
  • fixedRate: 定义每次任务之间的固定延迟时间(以毫秒为单位)。它会在前一个任务完成后立即开始下一个任务,而不考虑任务本身的执行时间。
  • fixedDelay: 类似于 fixedRate,但它是在前一个任务完成后等待指定的时间才开始下一个任务。
  • initialDelay: 设置第一次调度之前的延迟时间。

运行应用程序

当启动应用程序时,Spring Boot 会自动检测到带有 @Scheduled 注解的方法,并按照定义的时间规则执行它们。

相关推荐
2401_cf3 小时前
为什么hadoop不用Java的序列化?
java·hadoop·eclipse
帮帮志3 小时前
idea整合maven环境配置
java·maven·intellij-idea
LuckyTHP3 小时前
java 使用zxing生成条形码(可自定义文字位置、边框样式)
java·开发语言·python
热河暖男3 小时前
【实战解决方案】Spring Boot+Redisson构建高并发Excel导出服务,彻底解决系统阻塞难题
spring boot·后端·excel
无声旅者6 小时前
深度解析 IDEA 集成 Continue 插件:提升开发效率的全流程指南
java·ide·ai·intellij-idea·ai编程·continue·openapi
0吉光片羽06 小时前
【SpringBoot】集成kafka之生产者、消费者、幂等性处理和消息积压
spring boot·kafka·linq
Ryan-Joee6 小时前
Spring Boot三层架构设计模式
java·spring boot
Hygge-star6 小时前
【数据结构】二分查找5.12
java·数据结构·程序人生·算法·学习方法
dkmilk7 小时前
Tomcat发布websocket
java·websocket·tomcat
工一木子7 小时前
【Java项目脚手架系列】第七篇:Spring Boot + Redis项目脚手架
java·spring boot·redis