Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
597 views
in Technique[技术] by (71.8m points)

java - How to change Spring's @Scheduled fixedDelay at runtime?

I have a requirement to run a batch job at a fixed interval and have the ability to change the time of this batch job at runtime. For this I came across @Scheduled annotation provided under Spring framework. But I'm not sure how I'd change the value of fixedDelay at runtime. I did some googling around but didn't find anything useful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In spring boot, you can use an application property directly!

For example:

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

Note that you can also have a default value in case the property isn't defined, eg to have a default of "60" (seconds):

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

Other things I discovered:

  • the method must be void
  • the method must have no parameters
  • the method may be private

I found being able to use private visibility handy and used it in this way:

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

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

Being private, the scheduled method can be local to your service and not become part of your Service's API.

Also, this approach allows the process() method to return a value, which a @Scheduled method may not. For example, your process() method can look like:

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

to provide some information about what happened during processing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...