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

相关推荐
洛小豆7 分钟前
饭票、图书馆、GC:这样理解 Java 引用,谁还不会?
java·后端·面试
SimonLiu00923 分钟前
清理HiNas(海纳斯) Docker日志并限制日志大小
java·docker·容器
带刺的坐椅24 分钟前
开发 MCP Proxy(代理)也可以用 Solon AI MCP 哟!
java·ai·llm·solon·mcp·mcp-server·mcp-client
yuren_xia39 分钟前
Spring XML 配置
xml·java·spring
小鸡脚来咯1 小时前
SpringBoot 常用注解大全
java
风铃儿~1 小时前
Java面试高频问题(26-28)
java·算法·面试
IT瘾君1 小时前
Java基础:认识注解,模拟junit框架
java·开发语言·junit
风象南1 小时前
SpringBoot中3种内容协商策略实现
java·spring boot·后端
ん贤1 小时前
并发编程【深度解剖】
后端·go·并发
IT瘾君1 小时前
JavaWeb:Web介绍
java·web