无法在应用程序属性中设置 cron 作业计划。 SpringBoot ;使用调度程序在运行时调度 cron 作业

Unable to set the cron job schedule in application properties. SpringBoot ;scheduling of cron job at runtime using Scheduler

我正在尝试使用

安排我的休息服务(使用 GET 方法)

@Scheduled(cron = xyzzy.getTimeSchedule())

预计在应用程序启动期间从云端的应用程序属性中获取计划详细信息。但是我得到 "The value for Annotation attribute Scheduled.cron must be a constant expression" 编译时错误。请建议。还有什么可能是潜在的问题,比如 Spring 注释和应用程序启动期间可用的属性。请指导或引导我到 understand.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 注解

首先,自动装配 TaskScheduler 并确保使用 @EnableScheduling 注释对主要 class 进行注释,以便为 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"

最后这对我有用。 我将 属性 作为键存储:cloud.like 上的值对,所以..

xyz.Schedule = */5 * * * * ;

public Class testController {

@Autowired private Type type;

@Scheduled(cron = "${type.getSchedule()}") @GetMapping(path = "/", produces = "application/json") public void getmethod() { blah blah } }

我 运行 我的应用程序成功并且能够在应用程序开始时填充通过云配置的 属性,并且能够为我的 api 获得响应.

我尝试过的事情: 正如 Shekhar Rai 在此讨论链中所建议的那样,将其声明为最终变量,但无法在我的方法中访问它。

尝试将方法包装为可运行任务,但无法做到。

到达:@Scheduled.cron 总是需要一个常量参数(如字符串),但 get() 是动态的,因此将其包装为常量参数。

@ManagedConfiguration
private ConfigClass configClass;
    
@bean
public String getSchedulerValue() {
return configClass.getSchedule();}

@Scheduled(cron="#{getSchedulerValue}")