@Scheduled开启定时任务
时间: 2025-06-22 07:38:27 浏览: 19
### 如何使用 `@Scheduled` 注解配置和启动 Spring Boot 定时任务
#### 启用定时任务支持
为了使定时任务生效,在应用程序的主要配置类或启动类上需添加 `@EnableScheduling` 注解[^1]。
```java
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableScheduling
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
```
#### 创建定时任务组件
创建一个新的Java类用于定义具体的定时任务逻辑。此类应被Spring容器管理,因此需要加上 `@Component` 或其他合适的Scope注解[^3]。
```java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTasks {
// 按固定速率每5秒执行一次的任务
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("The time is now " + new Date());
}
// 使用Cron表达式每天凌晨一点钟运行的方法
@Scheduled(cron = "0 0 1 * * ?")
public void executeDailyTask() {
System.out.println("Executing daily task at midnight.");
}
}
```
上述例子展示了两种不同的调度方式:一种是以固定的间隔时间重复执行;另一种则是通过CRON表达式的灵活性指定更复杂的调度模式。
关于默认情况下使用的调度器是一个单线程实例,这意味着所有的计划任务将会顺序而非并发地被执行除非另有设置[^2]。
阅读全文
相关推荐



















