Reputation: 5031
in our system we use a settings class to point to the properties file, depends on which eve it loads different property file. To access specific property, we call 'Settings.getString('property_name_here')'.
In my code, i loaded the @scheduled cron expression to a variable and try to passed to the @scheduled annotation, but it won't work,
here is my code: in properties file:
cron.second=0
cron.min=1
cron.hour=14
in constructor i have:
this.cronExpression = new StringBuilder()
.append(settings.getString("cron.second"))
.append(" ")
.append(settings.getString("cron.min"))
.append(" ")
.append(settings.getString("cron.hour"))
.append(" ")
.append("*").append(" ").append("*").append(" ").append("*")
.toString();
which create a String of "0 1 14 * * *", it's a valid con expression
in the scheduled task i have:
@Scheduled(cron = "${this.cronExpression}")
public void scheduleTask() throws Exception {
....
}
when I ran the code it complaint: Caused by: java.lang.IllegalStateException: Encountered invalid @Scheduled method 'scheduleTask': Cron expression must consist of 6 fields (found 1 in "${this.cronExpression}")
then I changed this.cronExpression to a list of String:
this.cronExpression = Lists.newArrayList();
this.cronExpression.add(settings.getString("cron.second"));
this.cronExpression.add(settings.getString("cron.min"));
this.cronExpression.add(settings.getString("cron.hour"));
this.cronExpression.add("*");
this.cronExpression.add("*");
this.cronExpression.add("*");
but still got the same error, so what exactly is the cron expression supposed to be?
Upvotes: 11
Views: 20594
Reputation: 169
What I did and it worked for me:
In properties file:
my.cron.expression=0 3 * * * ?
In code:
@Scheduled(cron = "${my.cron.expression}")
public void scheduleTask(){
...
}
Upvotes: 14