【问题标题】:Is there way to use @Scheduled together with Duration string like 15s and 5m?有没有办法将@Scheduled 与 15s 和 5m 之类的 Duration 字符串一起使用?
【发布时间】:2020-05-04 07:31:51
【问题描述】:

我的代码中有以下注释

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

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

app.delay=10000 #10 sec

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

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

【问题讨论】:

    标签: java spring spring-boot scheduled-tasks spring-scheduled


    【解决方案1】:

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

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

    【讨论】:

    • 这对我不起作用。得到“不兼容的类型,发现 String 需要 Long”......但它适用于 fixedDelayString
    【解决方案2】:

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

    PT10S
    

    【讨论】:

    • 是的,它有效。但不幸的是 10s 不起作用,尽管 spring 能够将 10s 解析为 Duration
    【解决方案3】:

    据我所知,你不能直接这样做。但是,Spring 引导配置属性执行 support automatic conversion 等参数,例如 15s5mDuration

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

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

    【讨论】:

    • 能否请您检查一下您在此处使用的符号是否正确:@Scheduled(fixedDelayString = "#{@appProperties.getDelay().toMillis()}")
    • @gstackoverflow 你能解释一下你的意思吗?它不适合你吗?有什么不清楚吗?
    • 它对我不起作用。你能指定什么是bean名称,什么是属性键?
    • foo.bar.Bean 中构造函数的参数 0 需要一个名为“appProperties”的 bean,但无法找到。
    • 我解决了这个问题。这是因为我使用了 ConfigurationProperties("app") +EnableConfigurationProperties。 ConfigurationProperties + Component 是一个有效的组合
    猜你喜欢
    • 2016-12-23
    • 1970-01-01
    • 2018-07-06
    • 2020-11-05
    • 1970-01-01
    • 2018-03-15
    • 2016-11-01
    • 1970-01-01
    • 2018-09-07
    相关资源
    最近更新 更多