Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterizing Spring @Scheduled with default value

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?

like image 537
s1moner3d Avatar asked Aug 31 '16 11:08

s1moner3d


People also ask

What is @scheduled annotation in spring?

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.

How does @scheduled work in spring?

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.

What is @scheduled in Java?

Java Cron Expression The @Scheduled annotation is used to trigger the scheduler for a specific time period.


1 Answers

You can add the default value in the placeholder like this:

@Scheduled(cron = "${my.task.cron-exec-expr:*/5 * * * * *}")
like image 56
JEY Avatar answered Sep 17 '22 22:09

JEY