Spring Boot @Scheduled cron

非 Y 不嫁゛ 提交于 2019-12-09 05:20:14

问题


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}")

回答1:


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.




回答2:


@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 * * ?


来源:https://stackoverflow.com/questions/36204858/spring-boot-scheduled-cron

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!