SpringBoot使用@Scheduled注解实现定时任务

使用@Scheduled实现定时任务

在Spring Boot中,通过@Scheduled注解可以快速实现定时任务功能。以下是具体实现方式和相关配置说明。

基本配置方法

创建一个带有@Component注解的类,在需要定时执行的方法上添加@Scheduled注解。同时需要在主配置类上添加@EnableScheduling注解启用定时任务功能。

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

@Component
public class ScheduledTasks {
    
    @Scheduled(fixedRate = 5000)
    public void taskWithFixedRate() {
        System.out.println("Fixed Rate Task: " + System.currentTimeMillis());
    }
}
java 复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
常用调度属性

@Scheduled注解支持多种调度方式:

java 复制代码
@Scheduled(fixedRate = 5000)  // 固定速率执行
@Scheduled(fixedDelay = 3000) // 固定延迟执行
@Scheduled(cron = "0 15 10 * * ?") // Cron表达式

时区支持

通过 zone 参数指定时区,例如:
@Scheduled(cron = "0 0 12 * * ?", zone = "GMT+8") 表示北京时间12:00执行

时间间隔执行方式

固定速率执行是指上一次开始执行时间点之后固定时间间隔执行:

java 复制代码
@Scheduled(fixedRate = 60000) // 每分钟执行一次

固定延迟执行是指上一次执行结束时间点之后固定时间间隔执行:

java 复制代码
@Scheduled(fixedDelay = 30000) // 上次执行完成后30秒再执行
初始延迟配置

可以设置首次执行的延迟时间:

java 复制代码
@Scheduled(initialDelay = 10000, fixedRate = 60000) // 启动10秒后开始,之后每分钟执行
Cron表达式规则

Cron表达式包含6-7个字段(秒 分 时 日 月 周 年):

java 复制代码
@Scheduled(cron = "0 0 9 * * ?")  // 每天9点执行
@Scheduled(cron = "0 0/5 14,18 * * ?") // 每天14点和18点,每隔5分钟执行
@Scheduled(cron = "0 15 10 ? * MON-FRI") // 工作日10:15执行
相关推荐
涡能增压发动积21 小时前
同样的代码循环 10次正常 循环 100次就抛异常?自定义 Comparator 的 bug 让我丢尽颜面
后端
云烟成雨TD21 小时前
Spring AI Alibaba 1.x 系列【6】ReactAgent 同步执行 & 流式执行
java·人工智能·spring
Wenweno0o21 小时前
0基础Go语言Eino框架智能体实战-chatModel
开发语言·后端·golang
于慨21 小时前
Lambda 表达式、方法引用(Method Reference)语法
java·前端·servlet
swg32132121 小时前
Spring Boot 3.X Oauth2 认证服务与资源服务
java·spring boot·后端
tyung21 小时前
一个 main.go 搞定协作白板:你画一笔,全世界都看见
后端·go
gelald21 小时前
SpringBoot - 自动配置原理
java·spring boot·后端
@yanyu66621 小时前
07-引入element布局及spring boot完善后端
javascript·vue.js·spring boot
殷紫川21 小时前
深入理解 AQS:从架构到实现,解锁 Java 并发编程的核心密钥
java
一轮弯弯的明月21 小时前
贝尔数求集合划分方案总数
java·笔记·蓝桥杯·学习心得