前言
在实际开发中,我们经常需要实现定时任务的功能,例如每天凌晨执行数据清理、定时发送邮件等。Spring Boot 提供了非常便捷的方式来实现定时任务,本文将详细介绍如何在 Spring Boot 中使用定时任务。
一、Spring Boot 定时任务简介
Spring Boot 使用@Scheduled
注解来实现定时任务功能,底层基于 Spring 的任务调度模块(Spring Task)。通过该注解,我们可以很方便地定义周期性执行的任务。
二、启用定时任务
首先,在 Spring Boot 应用中要启用定时任务,需要在主启动类或配置类上添加 @EnableScheduling 注解:
@SpringBootApplication
@EnableScheduling
public class ScheduledTaskApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduledTaskApplication.class, args);
}
}
三、创建定时任务
接下来,我们可以通过 @Scheduled 注解来定义定时任务方法。这些方法必须是无参
的,并且返回类型为 void
。
@Component
public class ScheduledTasks {
// 每隔5秒执行一次
@Scheduled(fixedRate = 5000)
public void runEveryFiveSeconds() {
String time = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME);
System.out.println("Fixed rate task - Current time: " + time);
}
// 每天上午10:00执行
@Scheduled(cron = "0 0 10 * * ?")
public void runAtTenAM() {
String time = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME);
System.out.println("Daily task at 10 AM - Current time: " + time);
}
// 初始延迟3秒后执行,之后每隔10秒执行一次
@Scheduled(initialDelay = 3000, fixedDelay = 10000)
public void delayedTask() {
String time = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME);
System.out.println("Delayed task - Current time: " + time);
}
}
四、@Scheduled 支持的参数
参数名 | 描述 |
---|---|
fixedDelay | 上次任务执行完后,间隔固定时间再次执行(毫秒) |
fixedRate | 固定频率执行,无论上次任务是否完成 |
initialDelay | 初始延迟时间(毫秒),仅在首次执行时生效 |
cron | 使用 cron 表达式指定执行时间 |
Cron 表达式说明
Cron 表达式由6或7个字段组成,分别表示:
- 秒(0–59)
- 分(0–59)
- 小时(0–23)
- 日(1–31)
- 月(1–12 或 JAN–DEC)
- 周几(1–7 或 SUN–SAT)
- (可选)年份(1970–2099)
示例:“0 0 10 * * ?” 表示每天上午10点执行。
五、多线程支持
默认情况下,Spring Boot 的定时任务是单线程的,即多个任务会串行执行。如果你希望任务并行执行,可以自定义任务调度器:
@Configuration
@EnableScheduling
public class SchedulerConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(5); // 设置线程池大小
taskScheduler.initialize();
taskRegistrar.setTaskScheduler(taskScheduler);
}
}
六、注意事项
- 定时任务方法不能有返回值。
- 不建议在定时任务中执行耗时过长的操作,以免影响其他任务的执行。
- 如果部署在分布式环境下,需要考虑使用 Quartz 或 XXL-JOB 等分布式任务调度框架。
七、总结
Spring Boot 提供了非常简单易用的方式来实现定时任务功能。通过 @Scheduled
注解和 @EnableScheduling
启用定时任务,开发者可以快速构建定时任务逻辑。结合cron
表达式和线程池配置,可以满足大多数业务场景的需求。此外,如需更复杂的任务调度(如分布式环境下的任务协调),建议使用 Quartz 或 Spring Cloud Alibaba 的 XXL-JOB 等专业任务调度平台。