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.
To enable support for scheduling tasks and the @Scheduled annotation in Spring, we can use the Java enable-style annotation: @Configuration @EnableScheduling public class SpringConfig { ... }
To configure, batch job scheduling is done in two steps: Enable scheduling with @EnableScheduling annotation. Create method annotated with @Scheduled and provide recurrence details using cron job. Add the job execution logic inside this method.
Java Cron ExpressionThe @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file. The @Scheduled annotation is used to trigger the scheduler for a specific time period.
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:
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.
You can use a Trigger
to dynamically set the next execution time.
See my answer to Scheduling a job with Spring programmatically for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With