Normally I would do something like this to schedule a job to be periodically executed in Spring with cron in a given timezone:
@Scheduled(cron = "0 0 10 * * *", zone = "Europe/Stockholm")
public void scheduleStuff() {
// Do stuff
}
This is will block the thread calling scheduleStuff
until the job is completed. However in this case the "stuff" I want to do is all implemented using Springs' non-blocking building blocks of project reactor (i.e. Mono
, Flux
etc).
E.g. let's say that I want to trigger this function periodically:
Flux<Void> stuff() {
return ..
}
I can of course simply call stuff().subscribe()
(or even stuff().block()
) but this will block the thread. Is there a better way to achieve the same things as @Scheduled(cron = "0 0 10 * * *", zone = "Europe/Stockholm")
for non-blocking code?
I'm using Spring Boot 2.1.
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.
Configure batch job scheduler 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.
You can have multiple schedules as many as you need, and every one with its own schedule.
Actualy, subscribe()
doesn't block your thread. You could call stuff().subscribeOn(Schedulers.parallel()).subscribe()
or other scheduler to be sure that execution will be done in a separate thread, if you really need it.
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