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

瘦欲@ 提交于 2021-01-27 05:28:32

问题


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 ?


回答1:


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");
}

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



回答2:


You can just adjust your annotation to use a SpEL multiplication.

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



回答3:


Assuming you're using a recent enough version of Spring, you can use any String that can be parsed to a java.time.Duration. In your case:

PT10S


来源:https://stackoverflow.com/questions/59786883/is-there-way-to-use-scheduled-together-with-duration-string-like-15s-and-5m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!