@Scheduled(cron = "0 */10 * * * *")
时间: 2025-05-30 21:09:08 浏览: 19
### 关于 `@Scheduled(cron = "0 */10 * * * *")` 的解析
#### 表达式的结构
Cron 表达式由六个或七个字段组成,具体取决于是否包含年份字段。对于六字段的 Cron 表达式,其格式如下:
```
秒 分 时 日 月 星期
```
因此,表达式 `"0 */10 * * * *"` 可以分解为以下几个部分[^2]:
- **秒**: `0` —— 指定任务将在每一分钟的第 0 秒触发。
- **分**: `*/10` —— 每隔 10 分钟触发一次。
- **时**: `*` —— 每小时都会触发符合条件的任务。
- **日**: `*` —— 每天都会触发符合条件的任务。
- **月**: `*` —— 每个月都会触发符合条件的任务。
- **星期**: `*` —— 不区分具体的某一天(即每周每天都可能触发)。
这意味着此表达式定义了一个定时任务,在每个小时中的第 0、10、20、30、40 和 50 分钟的第 0 秒执行。
#### 实际应用案例
假设当前时间为 `2023-10-01 14:07:30`,当系统启动并加载带有此注解的方法后,第一次触发时间将是下一个满足条件的时间点,也就是 `2023-10-01 14:10:00`。之后每隔 10 分钟再次触发,例如 `14:20:00`, `14:30:00` 等等[^3]。
以下是基于 Spring Boot 使用的一个简单实现示例:
```java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class ScheduledTasks {
@Scheduled(cron = "0 */10 * * * *")
public void executeTask() {
System.out.println("Task executed at: " + new Date());
}
}
```
在此代码片段中,每当到达指定时间间隔时,控制台会打印出当前日期和时间戳来表明任务已被成功调度运行。
### 注意事项
需要注意的是,为了使 `@Scheduled` 注解生效,还需要在应用程序的主要配置类上启用计划功能支持,通常通过添加 `@EnableScheduling` 来完成这一过程[^1]。
```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);
}
}
```
阅读全文
相关推荐


















