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执行
相关推荐
IT_陈寒20 小时前
Redis持久化这个坑,我爬了一整天才出来
前端·人工智能·后端
无风听海20 小时前
多租户系统中的 OIDC:Discovery 端点与联合登录的深度实践
后端·python·flask
小小前端仔LC21 小时前
Node.js + LangChain + React:搭建个人知识库(六)- “吃什么”项目实战:从700+菜谱入库到Taro H5端JSON渲染
前端·后端
马士兵教育21 小时前
Java还有前景吗?Java+AI大模型学习路线及项目?
java·人工智能·python·学习·机器学习
程序员黑豆21 小时前
AI全栈开发之Java:怎么配置Java环境变量
前端·后端·ai编程
snow@li21 小时前
Java:理解 Gradle / 后端项目的管家 / 打包SpringBoot 应用 / 完成编译、下载依赖、运行测试、打包 JAR/WAR / 速查表
java
云烟成雨TD1 天前
Spring AI 1.x 系列【57】动态工具发现:Tool Search Tool
java·人工智能·spring
苍何1 天前
一手实测 Claude Fable 5,手搓了个 Obsidian 的 Codex 插件
后端
zfoo-framework1 天前
[修改代码使用]codex官方app中使用中转(不需要cc-switch) 1.config.toml 2.sk方式登录
java
逍遥德1 天前
MQTT教程详解-05.SpringBoot集成mqtt client 性能分析
java·spring boot·spring·mt