Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scheduling periodic reactive tasks in Spring using cron?

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.

like image 760
Johan Avatar asked Dec 18 '18 15:12

Johan


People also ask

How do I schedule a cron job in spring boot?

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.

How do you dynamically schedule a spring batch job?

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.

Can we have multiple scheduler in spring boot?

You can have multiple schedules as many as you need, and every one with its own schedule.


1 Answers

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.

like image 81
Alexander Pankin Avatar answered Sep 27 '22 22:09

Alexander Pankin