Spring Boot @Scheduled cron

ltalhouarne picture ltalhouarne · Mar 24, 2016 · Viewed 11.5k times · Source

Is there a way to call a getter (or even a variable) from a propertyClass in Spring's @Scheduled cron configuration? The following doesn't compile:

@Scheduled(cron = propertyClass.getCronProperty()) or @Scheduled(cron = variable)

I would like to avoid grabbing the property directly:

@Scheduled(cron = "${cron.scheduling}")

Answer

hovanessyan picture hovanessyan · Apr 5, 2016

Short answer - it's not possible out of the box.

The value passed as the "cron expression" in the @Scheduled annotation is processed in ScheduledAnnotationBeanPostProcessor class using an instance of the StringValueResolver interface.

StringValueResolver has 3 implementations out of the box - for Placeholder (e.g. ${}), for Embedded values and for Static Strings - none of which can achieve what you're looking for.

If you have to avoid at all costs using the properties placeholder in the annotation, get rid of the annotation and construct everything programmatically. You can register tasks using ScheduledTaskRegistrar, which is what the @Scheduled annotation actually does.

I will suggest to use whatever is the simplest solution that works and passes the tests.