[英]spring @scheduled cron with variable
在我们的系统中,我们使用一个设置类来指向属性文件,这取决于它加载不同属性文件的前夕。 要访问特定属性,我们调用'Settings.getString('property_name_here')'。
在我的代码中,我将@scheduled cron表达式加载到变量并尝试传递给@scheduled注释,但它不起作用,
这是我的代码:在属性文件中:
cron.second=0
cron.min=1
cron.hour=14
在构造函数中我有:
this.cronExpression = new StringBuilder()
.append(settings.getString("cron.second"))
.append(" ")
.append(settings.getString("cron.min"))
.append(" ")
.append(settings.getString("cron.hour"))
.append(" ")
.append("*").append(" ").append("*").append(" ").append("*")
.toString();
它创建一个字符串“0 1 14 * * *”,它是一个有效的con表达式
在预定的任务我有:
@Scheduled(cron = "${this.cronExpression}")
public void scheduleTask() throws Exception {
....
}
当我运行代码它抱怨:引起:java.lang.IllegalStateException:遇到无效的@Scheduled方法'scheduleTask':Cron表达式必须包含6个字段(在“$ {this.cronExpression}”中找到1)
然后我将this.cronExpression更改为String列表:
this.cronExpression = Lists.newArrayList();
this.cronExpression.add(settings.getString("cron.second"));
this.cronExpression.add(settings.getString("cron.min"));
this.cronExpression.add(settings.getString("cron.hour"));
this.cronExpression.add("*");
this.cronExpression.add("*");
this.cronExpression.add("*");
但仍然有同样的错误,那么cron表达式到底应该是什么?
我做了什么,它对我有用:
在属性文件中:
my.cron.expression=0 3 * * * ?
在代码中:
@Scheduled(cron = "${my.cron.expression}")
public void scheduleTask(){
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.