Spring Boot @Scheduled cron

前端 未结 2 1606
半阙折子戏
半阙折子戏 2020-12-16 00:17

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 compil

相关标签:
2条回答
  • 2020-12-16 00:46

    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.

    0 讨论(0)
  • 2020-12-16 00:59
    @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 * * ?
    
    0 讨论(0)
提交回复
热议问题