Using cron value from properties file in spring scheduler

Viewed 3021

I am using the Spring Schedular in my Spring Boot Application. I have defined the cron expression a properties file:

batch.delete-job.cron=0 0 0 * * *

I am using this value in my method annoated with the @Scheduled Annotation as follows:

@Scheduled(cron = "${batch.delete-job.cron}")
public void doBatchJob() {

}

I keep on getting the error messsage:

Encountered invalid @Scheduled method 'doBatchJob': Cron expression must consist of 6 fields (found 1 in "${batch.delete-job.cron}")

If I use the cron expression directly in annotation, then it works. What am I doing wrong?

3 Answers

Add this to your Application Context-

public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
       return new PropertySourcesPlaceholderConfigurer();
    }

If this dosent work try removing the hyphen in both the places(Your code and the application properties and seperate by .) For Eg-${batch.delete.job.cron}

Removing the hypen from the property name made no difference,but I did it anyway. What solved the problem was to put the following annotation referencing the properties file on my class containing the doBatchJob() method. The working solution looks as folllows:

@PropertySource("classpath:/config.properties")
@EnableScheduling
@Component
public class DeleteBatch {

  @Scheduled(cron = "${batch.delete.job.cron}")
  public void doBatchJob() {

  }
}

CRON is a widely used feature, but one of its disadvantages is poor readability. If a non-programmer needs to set a property that defines the scheduling it would be a challenging task. Imagine if you could write something like this: @Scheduled(fixedRate = 9h) for scheduling the job for every 9 hours (or moving "9h" into properties file). Well, I wrote my own feature that allows you to do just that. See the explanation here. This feature is available in MgntUtis open source library. The library is available as Maven artifact or from Git. Using this feature requires writing a bit more code then just using annotation, but provides a user-friendly format. So it is a trade-ff

Related