9

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?

user468587
  • 4,799
  • 24
  • 67
  • 124
  • 1
    Please take a look [here](https://stackoverflow.com/questions/36204858/spring-boot-scheduled-cron). I don't think what you are trying to achieve is supported (use a variable in this place). Maybe you can have in a property the complete cronExpression, and use it, if that is an option for you. – lzagkaretos Jan 19 '18 at 06:28
  • thanks, it explained everything – user468587 Jan 19 '18 at 16:41
  • Can you please also post the solution that you implemented in the end ? How did you managed to use the cron from a variable ? – Victor Sep 20 '18 at 13:41

1 Answers1

10

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(){
  ...
}
Joanna Kotuła
  • 129
  • 1
  • 6
  • 3
    Hi, The solution you posted works as a static cron and not essentially picked from a variable. It's just replacing the hardcoded value by reference in the property file. I – Tushar Banne Dec 06 '20 at 04:00
  • Yes, you are right. That was what I needed at the moment. And what I was looking for when I found this question ;) – Joanna Kotuła Dec 07 '20 at 12:15