spring boot 的同步定时任务可用 fixeddelaystring 指定间隔。上一轮方法执行结束后才开始计算等待时间,适合希望每轮之间留出固定空档的任务。
开启 Spring 调度
在 Spring Boot 3 项目的配置类启用调度。将类放在启动类能扫描到的包里。
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
class SchedulingConfig {}

在现有项目已有调度配置时,沿用该配置。
记录每轮开始和结束时间
在另一个组件文件加入以下方法。示例同步等待两秒,完成后再等三秒才调度下一次。
import java.time.Instant;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
class ReportTask {
@Scheduled(fixedDelayString = "${report.delay-ms:3000}")
public void run() {
System.out.println("start " + Instant.now());
try {
Thread.sleep(2000);
} catch (InterruptedException error) {
Thread.currentThread().interrupt();
} finally {
System.out.println("end " + Instant.now());
}
}
}
间隔的默认单位是毫秒。真实项目中将 sleep 换成同步业务操作。若方法只是把工作提交到异步线程,调度器会从提交方法返回时开始计时。
对照两次运行之间的间隔
用已有 Maven 项目启动应用,查看连续两轮日志。
./mvnw spring-boot:run
上一轮 end 到下一轮 start 应相隔约三秒。多实例会各自运行调度任务,需要按业务另行协调。











