那麻烦说下Spring Boot @Scheduled Cron 表达式 * /5 * * * ? 的执行频率到底是什么样子的
时间: 2025-07-10 18:01:31 浏览: 12
### 解析 Spring Boot 中 @Scheduled Cron 表达式 `*/5 * * * * ?`
#### 执行规则与频率
Cron 表达式由六个或七个字段组成,分别对应秒、分、小时、日期、月份、星期以及可选的年份。对于表达式 `*/5 * * * * ?`,其各字段的具体含义如下:
- **秒**: `*/5`
从第 0 秒开始,每隔 5 秒触发一次任务[^3]。
- **分**: `*`
每分钟都会触发任务,无特定限制。
- **小时**: `*`
每小时都会触发任务,无特定限制。
- **日期**: `*`
每天都会触发任务,无特定限制。
- **月份**: `*`
每个月都会触发任务,无特定限制。
- **星期**: `?`
不指定具体的星期几,表示每天都符合条件[^3]。
因此,该表达式的语义是:**每秒钟的第 0 秒开始,每隔 5 秒执行一次任务**。
---
#### 示例代码展示
以下是一个简单的 Spring Boot 应用程序示例,用于验证上述表达式的执行行为:
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
@SpringBootApplication
@EnableScheduling
public class ScheduleApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduleApplication.class, args);
}
@Scheduled(cron = "*/5 * * * * ?")
public void scheduledTask() {
System.out.println("Task executed at: " + new java.util.Date());
}
}
```
运行此应用程序后,控制台会显示类似于以下的日志输出:
```
Task executed at: Thu Oct 12 14:05:00 CST 2023
Task executed at: Thu Oct 12 14:05:05 CST 2023
Task executed at: Thu Oct 12 14:05:10 CST 2023
...
```
可以看到,任务确实按照预期,在每过 5 秒时被触发一次。
---
#### 注意事项
1. **时间单位一致性**
Cron 表达式的第一个字段始终代表秒,因此 `*/5` 明确指定了以秒为单位的时间间隔。
2. **线程安全性**
默认情况下,Spring 的定时任务是在同一个线程池中执行的。如果任务耗时较长,可能会导致后续任务延迟启动。可以通过自定义线程池来优化性能[^2]。
3. **时区问题**
如果未显式设置时区,默认使用服务器所在的操作系统时区。建议在生产环境中通过配置文件明确指定时区,例如:
```properties
spring.scheduler.timezone=Asia/Shanghai
```
---
### 总结
Cron 表达式 `*/5 * * * * ?` 的核心作用是以固定的 5 秒间隔重复执行任务。这种高频率的任务调度适用于实时性要求较高的场景,但在实现过程中需要注意资源占用和潜在的并发冲突等问题。
---
阅读全文
相关推荐


















