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

Tags: , , , ,



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 ?

Answer

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


Source: stackoverflow