问题
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