Spring Task 使用指南
1. 概念
Spring Task 是 Spring 框架提供的一套用于处理 定时任务和异步任务 的模块。它可以让我们在 Spring 应用中轻松地实现周期性任务、延迟任务或异步执行任务,而无需自己管理线程池或定时器。
Spring Task 核心特点:
- 轻量:直接使用 Spring 注解和配置即可。
- 集成度高:与 Spring Boot / Spring 框架无缝集成。
- 支持多种任务类型:支持 cron 表达式、固定延迟和固定频率的任务执行。
Spring Task 主要通过 @EnableScheduling 和 @Scheduled 注解实现。
2. 核心注解
2.1 @EnableScheduling
- 作用:启用 Spring 的任务调度功能。
- 使用位置:通常加在配置类或 Spring Boot 启动类上。
- 示例:
java
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
public class TaskConfig {
}
2.2 @Scheduled
- 作用:标注在方法上,表示该方法是一个定时任务。
- 属性:
| 属性 | 描述 |
|---|---|
fixedRate |
按固定频率执行(从方法开始执行算起,每隔多久执行一次) |
fixedDelay |
按固定延迟执行(从方法执行完毕算起,每隔多久执行一次) |
initialDelay |
初始延迟,方法第一次执行前的延迟时间 |
cron |
使用 Cron 表达式执行任务(可精确到秒) |
- 示例:
java
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class MyTask {
// 每隔 5 秒执行一次
@Scheduled(fixedRate = 5000)
public void fixedRateTask() {
System.out.println("Fixed rate task executed at " + System.currentTimeMillis());
}
// 方法执行完毕后延迟 3 秒再执行下一次
@Scheduled(fixedDelay = 3000)
public void fixedDelayTask() {
System.out.println("Fixed delay task executed at " + System.currentTimeMillis());
}
// Cron 表达式,每天 12:00 执行
@Scheduled(cron = "0 0 12 * * ?")
public void cronTask() {
System.out.println("Cron task executed at " + System.currentTimeMillis());
}
}
3. 配置线程池(可选)
默认情况下,Spring Task 使用单线程执行任务,如果有多个任务,可能会阻塞。为了提高性能,可以配置 线程池。
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@Configuration
public class TaskSchedulerConfig {
@Bean
public ThreadPoolTaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(5); // 设置线程池大小
scheduler.setThreadNamePrefix("my-scheduler-");
scheduler.setAwaitTerminationSeconds(60);
scheduler.setWaitForTasksToCompleteOnShutdown(true);
return scheduler;
}
}
配置线程池后,所有
@Scheduled注解的方法会使用该线程池执行。
4. Spring Boot 简化使用
在 Spring Boot 中,只需要:
- 添加依赖(通常已经自带
spring-boot-starter)。 - 在启动类上加
@EnableScheduling。 - 用
@Scheduled注解方法即可。
java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
5. 注意事项
- 方法必须为
void,且不能有参数。 - 方法所在的类必须被 Spring 管理 (加
@Component或其他 Spring Bean 注解)。 - Cron 表达式 :
- 秒(0-59)
- 分(0-59)
- 时(0-23)
- 日(1-31)
- 月(1-12)
- 星期(1-7 或 SUN-SAT)
- 线程安全:任务方法中如涉及共享资源,要注意线程安全。
- @Async 与 @Scheduled 配合 :可以实现异步定时任务,但需要启用
@EnableAsync并配置线程池。
6. 总结
Spring Task 提供了一套简单易用的定时任务框架,核心步骤:
- 启用任务调度
@EnableScheduling - 定义任务方法
@Scheduled - 可选:配置线程池提升性能
它适合轻量级任务、周期性任务和后台任务,非常适合 Spring Boot 应用。