简体   繁体   English

Java Spring MVC中@Scheduled注解中常量表达式的使用

[英]Use of constant expression in @Scheduled annotation in Java Spring MVC

I am using Spring MVC and I am trying to write a scheduled task that runs every hour.我正在使用 Spring MVC,我正在尝试编写一个每小时运行一次的计划任务。 The catch is that when the application starts up, it should calculate the duration until the next hour and use that value as a initial delay.问题是当应用程序启动时,它应该计算到下一小时的持续时间,并使用该值作为初始延迟。 This way, the scheduled task can run at exact hours like 1pm...2pm...3pm etc.这样,计划任务可以在确切的时间运行,例如 1pm...2pm...3pm 等。

In my code below, I tried to calculate the initial delay inside of a @PostConstruct annotation.在下面的代码中,我尝试计算 @PostConstruct 注释内的初始延迟。 However, when I try to use the variable inside of a @Scheduled annotation, I get the following error message: The value for annotation attribute Scheduled.initialDelay must be a constant expression但是,当我尝试在 @Scheduled 注释中使用变量时,我收到以下错误消息:注释属性 Scheduled.initialDelay 的值必须是常量表达式

private LocalDateTime now;
private  long delayUntilNextHour;
private long delayUntilNextDay;

@PostConstruct
public void initialize(){

    now = LocalDateTime.now();
    LocalDateTime nextHour = now.plusHours(1).withMinute(0).withSecond(0).withNano(0);
    delayUntilNextHour = now.until(nextHour, ChronoUnit.MILLIS);


}


@Scheduled(initialDelay= delayUntilNextHour, fixedRate=3600000) //Runs every hour
public void test(){
    //ADD LOGIC 
    hourMap.clear();
}

I cannot insert "delayUntilNextHour" into the initialDelay parameter of @Scheduled.我无法将“delayUntilNextHour”插入到@Scheduled 的initialDelay 参数中。 I was wondering if anyone can point me in the right direction in how to get around this.我想知道是否有人可以指出我如何解决这个问题的正确方向。

I have tried to make delayUntilNextHour a static final (constant), but it still does not work.我试图使 delayUntilNextHour 成为静态最终(常量),但它仍然不起作用。 I have also tried the string variant "initialDelayString", but that does not work either.我也尝试过字符串变体“initialDelayString”,但这也不起作用。

Use System.setProperty("delayUntilNextDay", delayUntilNextHour.toString());使用System.setProperty("delayUntilNextDay", delayUntilNextHour.toString()); inside the initialize() method and use @Value("${delayUntilNextDay}") to access the valueinitialize()方法中并使用@Value("${delayUntilNextDay}")访问该值

@Scheduled(initialDelay= @Value("${delayUntilNextDay}"), fixedRate=3600000) //Runs every hour
public void test(){
    //ADD LOGIC 
    hourMap.clear();
}

I haven't tried the above code.上面的代码我没试过。

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

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