gpt4 book ai didi

java - 有没有办法将 @Scheduled 与 Duration 字符串(如 15s 和 5m)一起使用?

转载 作者:行者123 更新时间:2023-11-30 05:19:34 25 4
gpt4 key购买 nike

我的代码中有以下注释

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

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

app.delay=10000 #10 sec

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

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

最佳答案

据我所知,你不能直接这样做。但是,Spring boot 配置属性确实support automatic conversion 15s5m 等参数到 Duration

这意味着您可以创建一个 @ConfigurationProperties 类,如下所示:

@Component
@ConfigurationProperties("app")
public class AppProperties {
private Duration delay;

// Setter + Getter
}

此外,因为您可以使用 bean references with Spring's Expression Language@Scheduled 注释中,您可以执行以下操作:

@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());
}

关于java - 有没有办法将 @Scheduled 与 Duration 字符串(如 15s 和 5m)一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59786883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com