【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 注解的方法,并按照定义的时间规则执行它们。

相关推荐
ping某9 分钟前
为什么 Nginx 明明监听了 80,转发后端时却用了 4xxxx 端口?
后端·nginx
JustHappy14 分钟前
我汇总了身边朋友的经历才发现,其实第一份实习是最难找的......
前端·后端·面试
uhakadotcom23 分钟前
在python 的 工程化架构中 ,什么是 薄包装器层?
后端·面试·github
唐青枫4 小时前
Java JDBC 实战指南:从 Connection 到事务和连接池
java
用户1474853079745 小时前
CodeX使用Skill生成游戏美术和音乐资源,一分钟入门
后端
Melody1235 小时前
用 abort 中断 AI 流式请求,我之前做错了
后端
onething3655 小时前
Spring Boot + Spring AI 从入门到实战:7天转型计划 Day 5 —— SSE 流式输出 + 打字机效果
人工智能·后端·全栈
一个做软件开发的牛马5 小时前
MyBatis-Plus 从零实战:完整搭建可运行 Demo,BaseMapper 零 SQL、Wrapper 条件构造、分页插件与代码生成器详解
java·后端
用户3721574261355 小时前
Java 处理 PDF 图片:提取 PDF 中的图片,并压缩 PDF 图片体积
java
码事漫谈6 小时前
AI 编程的「三体」架构:OpenSpec + Superpowers + GStack 如何让一个开发者撑起整个研发团队
后端