繁体   English   中英

Spring Boot @Scheduled cron

[英]Spring Boot @Scheduled cron

有没有办法从 Spring 的@Scheduled cron配置中的 propertyClass 调用 getter(甚至变量)? 以下不编译:

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

我想避免直接抢财产:

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

简短的回答 - 开箱即用是不可能的。

@Scheduled注释中作为“cron 表达式”传递的值在ScheduledAnnotationBeanPostProcessor类中使用StringValueResolver接口的实例进行处理。

StringValueResolver有 3 个开箱即用的实现 - 用于Placeholder (例如 ${})、用于Embedded值和用于Static字符串 - 没有一个可以实现您正在寻找的东西。

如果您必须不惜一切代价避免在注释中使用属性占位符,请摆脱注释并以编程方式构建所有内容。 您可以使用ScheduledTaskRegistrar注册任务,这正是@Scheduled注释的实际作用。

我会建议使用任何可以工作并通过测试的最简单的解决方案。

如果您不想从属性文件中检索 cron 表达式,您可以按如下方式以编程方式进行:

// Constructor
public YourClass(){
   Properties props = System.getProperties();
   props.put("cron.scheduling", "0 30 9 * * ?");
}

这允许您在不进行任何更改的情况下使用您的代码:

@Scheduled(cron = "${cron.scheduling}")
@Component
public class MyReminder {

    @Autowired
    private SomeService someService;

    @Scheduled(cron = "${my.cron.expression}")
    public void excecute(){
        someService.someMethod();
    }
}

在 /src/main/resources/application.properties

my.cron.expression = 0 30 9 * * ?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM