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执行
相关推荐
TSuperman13 分钟前
一次由高危漏洞引发的 Nginx 1.30.7 跨发行版安全升级实战
后端
静水深码26 分钟前
文生图提示词的工程师写法:把玄学话术拆成结构化模板
人工智能·后端·代码规范
码云社区1 小时前
Java在线租房系统源码:VR看房素材、房源图片与内容维护方案
java·vue.js·vr·租房小程序·在线租房·看房租房
码云社区2 小时前
Spring Boot智慧物业系统源码:合同到期提醒、续签资料与资产协作
java·spring boot·后端·物业管理·物业系统·智慧物业
AI开源软件2 小时前
Vue3+SpringBoot3 业务配置统一管理:接管、保存与回退怎样保留有效值
java·前端·vue.js·spring boot·vue·ruoyi office
陈如水2 小时前
Spring AI Alibaba 在多 Agent 场景下的实践
java·人工智能·spring
旋律4142 小时前
数据倾斜
后端
杨运交2 小时前
091-功能模块-API Key 管理功能模块解析:feature-sa-token 架构设计与数据库持久化
spring boot
泡海椒3 小时前
jquick-pdf 热力图实战:Object 数组三元素的数据契约与模板还原
后端
行百里er3 小时前
【Spring Insight 技术分享】如何给 AI 接口调用做滑动窗口限流
spring boot·后端·spring cloud