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执行
相关推荐
苏三说技术2 小时前
LangChain4j 和 LangGraph4j,哪个更好?
后端
ServBay3 小时前
7 个AI开发中真正用得上的 MCP Server,配合Claude Code食用效果更佳
后端·claude·mcp
妙码生花3 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十五):优化细节、网络请求封装
前端·后端·ai编程
用户6757049885024 小时前
Go 语言里判断字符串为空,90% 的人都写错了!
后端·go
Flittly4 小时前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
用户6757049885024 小时前
Go 进阶必修:90% 的人都没用对的“表驱动法”
后端·go
小兔崽子去哪了4 小时前
Java 生成二维码解决方案
java·后端
苍何4 小时前
懂事的 Agent 已经开始自己看屏幕干活了,效率起飞!
后端
掘金码甲哥4 小时前
1分钟买不了吃亏系列: nginx动态域名解析
后端