SuperAPI AI 工具集

spring-scheduling

部署与运维

查看项目

更新于 10-15 18:52

技能介绍

用途:面向 Spring Boot 3.x 的定时任务(Scheduling)与异步执行(Async)开发参考,帮助配置 @Scheduled 定时任务、@Async 异步方法、线程池与分布式调度。

主要能力:

  1. @Scheduled:支持 fixedRate(按上次开始时间间隔执行)、fixedDelay(上次完成后延迟执行)、initialDelay、fixedRateString 属性化配置、timeUnit,以及 cron 表达式(含时区 zone,用 "-" 禁用任务)。cron 为六段式:秒 分 时 日 月 周。
  2. @Async:支持 fire-and-forget 与返回 CompletableFuture 的异步方法,可指定执行器 @Async("reportExecutor")。
  3. 线程池:通过 ThreadPoolTaskExecutor 配置 corePoolSize、maxPoolSize、queueCapacity、threadNamePrefix、拒绝策略、优雅关闭(waitForTasksToCompleteOnShutdown、awaitTerminationSeconds);也可用 spring.task.execution.pool 与 spring.task.scheduling.pool 属性配置。

使用方式:在启动类加 @EnableScheduling 与 @EnableAsync;实现 AsyncConfigurer 提供 getAsyncExecutor;用 @Scheduled 与 @Async 标注方法。

适用场景:定时批处理、周期任务、异步邮件/报表生成、集群环境下的分布式调度。

限制与注意:资料提及需用 ShedLock 处理集群重复执行、配置错误处理器、监控执行时间、优雅关闭、瞬时失败重试;常见反模式包括缺少 @EnableScheduling、内部调用 @Async 导致代理失效、任务重叠、线程池过小、void 异步无异常处理。分布式调度、动态调度与测试细节见 async.md 与 distributed.md,本资料未展开。