我正在尝试使用
安排我的休息服务(使用 GET 方法)@Scheduled(cron = xyzzy.getTimeSchedule())
预计在应用程序启动期间从云端的应用程序属性中获取计划详细信息。但是我得到“注释属性 Scheduled.cron 的值必须是常量表达式”编译时错误。请建议。还有什么可能是潜在的问题,比如 Spring 注释和应用程序启动期间可用的属性。请指导或指导我理解.TIA。
最佳答案
使用 @Scheduled注释您不能为来自云的 cron-expression 提供方法。由于java注解需要constant-expression,这是一个一旦赋值就不能改变的变量。为此,您需要使用 final
关键字。
public static final String TIME_SCHEDULE = "0 0/30 8-10 * * *";
然后在您的调度程序方法中使用该常量表达式,
@Scheduled(cron = TIME_SCHEDULE)
在你的情况下,你应该去 @TaskScheduler (来自文档)
Task scheduler interface that abstracts the scheduling of Runnables based on different kinds of triggers. This interface is separate from SchedulingTaskExecutor since it usually represents for a different kind of backend, i.e. a thread pool with different characteristics and capabilities. Implementations may implement both interfaces if they can handle both kinds of execution characteristics.
用@TaskScheduler 替换@Scheduled 注解
首先, Autowiring TaskScheduler 并确保您使用 @EnableScheduling 注释了您的主类注释为 TaskScheduler 提供 bean。
@Autowired
private TaskScheduler scheduler;
现在您需要安排提供 Runnable 和 CronTrigger争论。它调度给定的 Runnable,每当触发器指示下一个执行时间时调用它。
这意味着您需要将您的逻辑(目前这是来自您的@Schduled 方法主体的代码)包装到 Runnable 实例中。您的 xyzzy.getTimeSchedule()
应该提供给 CronTrigger 构造函数。
Runnable runnableTask = () -> {
//call REST API here
};
scheduler.schedule(runnableTask, new CronTrigger(xyzzy.getTimeSchedule());
Now you get rid of "The value for Annotation attribute Scheduled.cron must be a constant expression"
关于spring-boot - 无法在应用程序属性中设置 cron 作业计划。 SpringBoot ;使用调度程序在运行时调度 cron 作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59444871/