有没有办法将@Scheduled 与像 15s 和 5m 这样的 Duration 字符串一起使用? [英] Is there way to use @Scheduled together with Duration string like 15s and 5m?

查看:61
本文介绍了有没有办法将@Scheduled 与像 15s 和 5m 这样的 Duration 字符串一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有以下注释

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

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

app.delay=10000 #10 秒

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

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

解决方案

据我所知,你不能直接做.但是,Spring 启动配置属性会 支持15s5m等参数自动转换Duration.>

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

@Component@ConfigurationProperties(应用程序")公共类 AppProperties {私人时间延迟;//设置器 + 获取器}

此外,由于您可以使用 bean 引用,您可以执行以下操作:

@Scheduled(fixedDelayString = "#{@appProperties.getDelay().toMillis()}")公共无效时间表(){log.info(预定");}

注意:使用这种方法时,您必须使用 @Component 注释注册您的配置属性.如果您使用 @EnableConfigurationProperties 注释,它将不起作用.


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

@Bean公共预定未来schedule(TaskScheduler 调度程序,AppProperties 属性){return scheduler.scheduleWithFixedDelay(() -> log.info(Scheduled"), properties.getDelay());}

I have following annotation in my code

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

At this case I have to have properties like this

app.delay=10000 #10 sec

Propery file looks unreadable because I have calculate value to miliseconds.

Is there way to pass value like 5m or 30s there ?

解决方案

As far as I know, you can't do it directly. However, Spring boot configuration properties do support automatic conversion of parameters like 15s and 5m to Duration.

This means you could create a @ConfigurationProperties class like this:

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

    // Setter + Getter
}

Additionally, since you can use bean references with Spring's Expression Language within the @Scheduled annotation, you can do something like this:

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

Note: When using this approach, you have to register your configuration properties using the @Component annotation. It won't work if you use the @EnableConfigurationProperties annotation.


Alternatively, you can programmatically add a task to the TaskScheduler. The benefit of that is that you have more compile-time safety, and it allows you to work with Duration directly:

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

这篇关于有没有办法将@Scheduled 与像 15s 和 5m 这样的 Duration 字符串一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆