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 小时前
零基础入门 Redis:从“缓存是什么”到手写一个简易购物车系统
java·spring boot·redis·缓存·编程入门·小白教程
短剑重铸之日2 小时前
《SpringCloud实用版》完整技术选型地图
java·后端·spring·spring cloud
咚为2 小时前
Rust 错误处理的工程化演进:从 Result 到系统级边界设计
开发语言·后端·rust
南山乐只2 小时前
Qwen Code + OpenSpec 实战指南:AI 驱动开发的从安装到落地
java·人工智能·后端
有味道的男人2 小时前
如何使用招标网API获取项目详情?
java·服务器·前端
小北方城市网3 小时前
Spring Cloud 服务治理实战:构建高可用微服务体系
spring boot·python·rabbitmq·java-rabbitmq·数据库架构
代码写到35岁3 小时前
【Java 单体架构改造 微服务 网关遇坑之 跨域配置】
java·微服务·架构
qq_12498707533 小时前
基于Java的心理测试系统的设计与实现(源码+论文+部署+安装)
java·开发语言·vue.js·spring boot·计算机毕设·计算机毕业设计
拽着尾巴的鱼儿3 小时前
Spring定时任务 Scheduled使用
java·后端·spring