java - 有没有办法将@Scheduled 与 15s 和 5m 之类的 Duration 字符串一起使用?
问题描述
我的代码中有以下注释
@Scheduled(fixedDelayString = "${app.delay}")
在这种情况下,我必须有这样的属性
app.delay=10000 #10 sec
属性文件看起来不可读,因为我已经将值计算到毫秒。
有没有办法传递像 5m 或 30s 这样的值?
解决方案
据我所知,你不能直接这样做。但是,Spring 引导配置属性确实支持参数的自动转换,例如15s
和。5m
Duration
这意味着您可以创建这样的@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());
}
推荐阅读
- javascript - NodeJS mongoose - 将整个集合复制到另一台服务器中的数据库
- java - 彩色打印后在java中输入
- ios - Swift UISlider 多种轨道颜色
- python - Python仅将邮件发送到Excel工作表中的最后一个邮件地址
- javascript - 如何在循环后将总和除以 2
- sql - 仅由内部联接 SQL 中的 no_member 显示列表数据事务 MAX(transaction_id)
- mule - 尝试在 Exchange 目标部署文件上部署 Mule4 策略未找到
- node.js - 使用 lerna 为 react 和 node js web 应用程序实现 monorepo
- php - 从 aws 随机获取 net::ERR_CONNECTION_RESET
- selenium-webdriver - Selenium Xpath 使用 gettext() 方法中的值不起作用