Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Scheduled and Spring webflux

I'm searching a way to use scheduled tasks in a reactive API. I know that it uses the thread pool so it's not very compatible with the webflux components.

Do you have an equivalent to do the job?

like image 539
Saveriu CIANELLI Avatar asked Jan 08 '19 13:01

Saveriu CIANELLI


People also ask

Can I use Springmvc and WebFlux together?

There are several reasons for this: Spring MVC can't run on Netty. both infrastructure will compete for the same job (for example, serving static resources, the mappings, etc) mixing both runtime models within the same container is not a good idea and is likely to perform badly or just not work at all.

What is @scheduled in Spring?

Spring Core. Spring provides excellent support for both task scheduling and asynchronous method execution based on cron expression using @Scheduled annotation. The @Scheduled annotation can be added to a method along with trigger metadata.

What is @scheduled annotation in Spring?

The @EnableScheduling annotation is used to enable the scheduler for your application. This annotation should be added into the main Spring Boot application class file. @SpringBootApplication @EnableScheduling public class DemoApplication { public static void main(String[] args) { SpringApplication.

Does Tomcat support Spring WebFlux?

Spring WebFlux is also supported on a traditional Servlet Container like Apache Tomcat.


2 Answers

You may try to use Schedulers.immediate() inside @Scheduled method:

doWork()
  .subscribeOn(Schedulers.immediate())
  .subscribe()

As a consequence tasks run on the thread that submitted them.

like image 183
jreznot Avatar answered Sep 16 '22 12:09

jreznot


There are several ways to do. Considering how you want to schedule it you can use following as well.

@Configuration
class ApplicationConfiguration() {

    @PostConstruct
    fun init() {

        Flux.interval(Duration.ofMinutes(12))
            .onBackpressureDrop()
            .flatMap { /* some task that return Mono<T> */ }
            .subscribeOn(Schedulers.boundedElastic())
            .subscribe()
    }
}

Please note subscribeOn(Schedulers.boundedElastic()) is not required unless the call is blocking. Also I am using onBackpressureDrop but your requirements may be different than that.

like image 37
nicholasnet Avatar answered Sep 17 '22 12:09

nicholasnet