I need to parameterize a @Scheduled
method with value from my properties file if present, or default value if not.
We can parameterize from configuration file property in the following way:
@Scheduled(cron = "${my.task.cron-exec-expr}")
public void scheduledTask() {
// do something
}
but if the property does not exist we'll have a runtime exception.
I've tried using a @ConfigurationProperties
bean with default value, with no success:
@Component
@ConfigurationProperties(prefix = "my.task")
public class MyTaskProperties {
private String cronExecExpr = "*/5 * * * * *";
// getter and setter
}
How to avoid that and pass a default value?
The Scheduled annotation defines when a particular method runs. This example uses fixedRate , which specifies the interval between method invocations, measured from the start time of each invocation.
We can turn any method in a Spring bean for scheduling by adding the @Scheduled annotation to it. The @Scheduled is a method-level annotation applied at runtime to mark the method to be scheduled. It takes one attribute from cron , fixedDelay , or fixedRate for specifying the schedule of execution in different formats.
Java Cron Expression The @Scheduled annotation is used to trigger the scheduler for a specific time period.
You can add the default value in the placeholder like this:
@Scheduled(cron = "${my.task.cron-exec-expr:*/5 * * * * *}")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With