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

Is there way to use @Scheduled together with Duration string like 15s and 5m?

我的代码中有以下注释

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

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

app.delay=10000 #10 sec

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

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

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

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

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

PT10S

据我所知,你不能直接这样做。但是,Spring 引导配置属性对 15s5mDuration.

等参数执行 support automatic conversion

这意味着您可以像这样创建 @ConfigurationProperties class:

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

    // Setter + Getter
}

此外,由于您可以在 @Scheduled 注释中使用 bean references with Spring's Expression Language,因此您可以这样做:

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