如何在运行时更改Spring的@ScheduledfixedDelay?

2024-02-17

我需要以固定的时间间隔运行批处理作业,并且能够在运行时更改该批处理作业的时间。为此我遇到了@ScheduledSpring框架下提供的注解。但我不确定如何在运行时更改fixedDelay 的值。我做了一些谷歌搜索,但没有发现任何有用的东西。


在 Spring Boot 中,您可以直接使用应用程序属性!

例如:

@Scheduled(fixedDelayString = "${my.property.fixed.delay.seconds}000")
private void process() {
    // your impl here
}

请注意,如果未定义该属性,您也可以使用默认值,例如默认值为“60”(秒):

@Scheduled(fixedDelayString = "${my.property.fixed.delay.seconds:60}000")

我发现的其他事情:

  • 该方法必须为空
  • 该方法必须没有参数
  • 该方法可能是private

我发现能够使用private可见性很方便并以这种方式使用它:

@Service
public class MyService {
    public void process() {
        // do something
    }

    @Scheduled(fixedDelayString = "${my.poll.fixed.delay.seconds}000")
    private void autoProcess() {
        process();
    }
}

Being private,计划的方法可以是您的服​​务的本地方法,并且不会成为您的服务 API 的一部分。

此外,这种方法允许process()方法返回一个值,其中@Scheduled方法可能不会。例如,您的process()方法可以如下所示:

public ProcessResult process() {
    // do something and collect information about what was done
    return processResult; 
}

提供有关处理过程中发生的情况的一些信息。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在运行时更改Spring的@ScheduledfixedDelay? 的相关文章

随机推荐