首页 > 解决方案 > 有没有办法将@Scheduled 与 15s 和 5m 之类的 Duration 字符串一起使用?

问题描述

我的代码中有以下注释

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

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

app.delay=10000 #10 sec

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

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

标签: javaspringspring-bootscheduled-tasksspring-scheduled

解决方案


据我所知,你不能直接这样做。但是,Spring 引导配置属性确实支持参数的自动转换,例如15s和。5mDuration

这意味着您可以创建这样的@ConfigurationProperties类:

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

    // Setter + Getter
}

此外,由于您可以在注解中使用带有 Spring 表达式语言的 bean 引用@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());
}

推荐阅读