有没有办法将@Scheduled与 15s 和 5m 等持续时间字符串一起使用?



我的代码中有以下注释

@Scheduled(fixedDelayString = "${app.delay}")

在这种情况下,我必须拥有这样的属性

app.delay=10000 #10 sec

属性文件看起来不可读,因为我已将值计算为毫秒。

有没有办法在那里传递 5m 或 30s 这样的值?

据我所知,你不能直接做。但是,Spring 引导配置属性确实支持将15s5m等参数自动转换为Duration

这意味着您可以像这样创建一个@ConfigurationProperties类:

@Component
@ConfigurationProperties("app")
public class AppProperties {
private Duration delay;
// Setter + Getter
}

此外,由于您可以在@Scheduled注释中使用 Spring 表达式语言的 Bean 引用,因此您可以执行以下操作:

@Scheduled(fixedDelayString = "#{@appProperties.getDelay().toMillis()}")
public void schedule() {
log.info("Scheduled");
}

: 使用此方法时,必须使用@Component注释注册配置属性。如果您使用@EnableConfigurationProperties注释,它将不起作用。


或者,可以通过编程方式将任务添加到TaskScheduler。这样做的好处是你有更多的编译时安全性,它允许你直接使用Duration

@Bean
public ScheduledFuture<?> schedule(TaskScheduler scheduler, AppProperties properties) {
return scheduler.scheduleWithFixedDelay(() -> log.info("Scheduled"), properties.getDelay());
}

假设你使用的是足够新的 Spring 版本,你可以使用任何可以解析为java.time.Duration的字符串。在您的情况下:

PT10S

我正在使用这段代码,它工作正常:

@Scheduled(fixedDelayString = "PT10S")

您可以调整注释以使用 SpEL 乘法。

@Scheduled(fixedDelayString = "#{${app.delay} * 1000}")

最新更新