Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running each Spring Scheduler in its own thread

I have multiple components with @Scheduled annotations, and I see that Spring only starts one at a time, even if they are scheduled to run on the same time.

My use case is as follows. I want each @Scheduled annotation to run in its own thread, but only once for each thread.

Given this pseudo code with two schedulers:

@Scheduled(cron = "0 * * * * *") //run every minute
public void methodA() {
   log.info("Running method A");
   executeLongRunningJob("Finished method A");
}

@Scheduled(cron = "0 * * * * *") //run every minute
public void methodB() {
   log.info("Running method B");
   executeLongRunningJob("Finished method B");       
}

private void executeLongRunningJob(String msg) {
    Thread.sleep(70 seconds);
    System.out.println(msg);
}

Note that the task takes longer time than the scheduler is scheduled to run. This is crucial. I don't want the scheduler to start again before its finished running.

Running this code out of the box gives me this output:

Running method A
Finished method A
Running method B
Finished method B
Running method A
Finished method A
Running method B
Finished method B
... and so on

So obviously its running both schedulers in a single thread.


When I put @Async on my expensive method, then I almost get the correct behavior, except the expensive method is not finished before a new scheduler is started.

Running method A
Running method B
Running method A
Running method B
Finished method A
Finished method B
... and so on

What I would like is this output:

Running method A  
Running method B
Finished method A 
Finished method B 
Running method A 
Running method B 
Finished method A 
Finished method B
... and so on

How can I accomplish this? I want each Scheduler to run concurrently, but wait until it is finished before allowed to run again. Remember I have more than two Schedulers running in same and sometimes different times.

like image 730
Shervin Asgari Avatar asked Jul 18 '17 17:07

Shervin Asgari


People also ask

Is Spring scheduler single threaded?

By default, Spring uses a local single-threaded scheduler to run the tasks. As a result, even if we have multiple @Scheduled methods, they each need to wait for the thread to complete executing a previous task.

Can we have multiple scheduler in Spring boot?

We can deploy multiple Scheduler Instances using the ShedLock library which ensures only one instance to run at a time by using a locking mechanism in a shared database.

How do I schedule a Spring boot thread?

Spring Boot provides different scheduling functionalities in spring applications. You can schedule your tasks via @Scheduled annotation or via using a custom thread pool. @EnableScheduling annotation ensures that a background task executor is created with single thread.


1 Answers

You're right - by default scheduler uses a thread pool with size 1, so every task is being processed sequentially. You can it by configuring TaskScheduler bean with desired pool size. Consider following example:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.Date;

@SpringBootApplication
@EnableScheduling
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public TaskScheduler taskScheduler() {
        final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(10);
        return scheduler;
    }


    @Scheduled(fixedDelay = 2 * 1000L, initialDelay = 3 * 1000L)
    public void scheduled1() throws InterruptedException {
        System.out.println(new Date() + " " + Thread.currentThread().getName() + ": scheduled1");
        Thread.sleep(1000);
    }

    @Scheduled(fixedDelay = 3 * 1000L, initialDelay = 3 * 1000L)
    public void scheduled2() throws InterruptedException {
        System.out.println(new Date() + " " + Thread.currentThread().getName() + ": scheduled2");
        Thread.sleep(1000);
    }
}

It will run every scheduled task in a separate thread, for example:

Tue Jul 18 20:21:50 CEST 2017 taskScheduler-1: scheduled2
Tue Jul 18 20:21:50 CEST 2017 taskScheduler-2: scheduled1
Tue Jul 18 20:21:53 CEST 2017 taskScheduler-1: scheduled1
Tue Jul 18 20:21:54 CEST 2017 taskScheduler-3: scheduled2
Tue Jul 18 20:21:56 CEST 2017 taskScheduler-2: scheduled1
Tue Jul 18 20:21:58 CEST 2017 taskScheduler-4: scheduled2
Tue Jul 18 20:21:59 CEST 2017 taskScheduler-1: scheduled1
like image 182
Szymon Stepniak Avatar answered Sep 19 '22 00:09

Szymon Stepniak