Spring Boot @Scheduled cron

Is there a way to call getter (or even a variable) from the @Scheduled property in the Spring @Scheduled cron configuration? The following does not compile:

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

I would like to avoid capturing the property directly:

 @Scheduled(cron = "${cron.scheduling}") 
+7
spring spring-boot cron schedule
source share
2 answers

The short answer is impossible out of the box.

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

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

If you need to avoid using the property attribute in the annotation at all costs, get rid of the annotation and build everything programmatically. You can register tasks using ScheduledTaskRegistrar , which is what the @Scheduled annotation @Scheduled .

I suggest using everything that is the simplest solution that works and passes the tests.

+5
source share
 @Component public class MyReminder { @Autowired private SomeService someService; @Scheduled(cron = "${my.cron.expression}") public void excecute(){ someService.someMethod(); } } 

in / src / main / resources / application.properties

 my.cron.expression = 0 30 9 * * ? 
-2
source share

All Articles