Spring Scheduler

Jul 26, 2021

Purpose

The purpose of this document is to learn and play around with spring's scheduling capabilities using @EnableScheduling annotation.

Use Case

You have 3 tasks to perform every minute and each task takes 10 seconds to complete.

How would you do it?

Add @EnableScheduling annotation to the class with @SpringBootApplication. Now @Configuration classes with @Scheduled methods will be enabled. (todo - any class)

  1. Go to https://start.spring.io/ and create a new application - scheduling.

  2. Add @EnableScheduling to SchedulingApplication.

  3. Add 3 @Configuration classes - One, Two & Three with a work() method.

    @Scheduled(fixedDelay = 60000)
    void work() throws InterruptedException {
        LOG.info("first one");
    }
    
  4. Run it.

    2021-07-26 07:45:03.687  INFO 91778 --- [   scheduling-1] com.example.scheduling.schedulers.One    : first one
    2021-07-26 07:45:03.687  INFO 91778 --- [   scheduling-1] com.example.scheduling.schedulers.Two    : second one
    2021-07-26 07:45:03.687  INFO 91778 --- [   scheduling-1] com.example.scheduling.schedulers.Three  : third one
    

The “first one”, “second one” and the “third one” log almost simultaneously.

You might have noticed “scheduling-1” associated with the three logs, which means a single thread worked on all of them. Is this a problem?

Let's find out by adding Thread.sleep(10000); before the log.

2021-07-26 07:59:35.899  INFO 91831 --- [   scheduling-1] com.example.scheduling.schedulers.One    : first one
2021-07-26 07:59:45.900  INFO 91831 --- [   scheduling-1] com.example.scheduling.schedulers.Two    : second one
2021-07-26 07:59:55.900  INFO 91831 --- [   scheduling-1] com.example.scheduling.schedulers.Three  : third one

Yes! There is a delay.

We're gonna need more threads!

Enter SchedulingConfigurer interface which helps us customize the executor and define more threads.

@Configuration
public class SchedulingConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar str) {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(10);
        scheduler.setThreadNamePrefix("scheduled-task-pool-");
        scheduler.initialize();

        str.setTaskScheduler(scheduler);
    }   
}

Add this class and run it and everything is gooooood again.

2021-07-26 08:04:03.479  INFO 91877 --- [led-task-pool-2] com.example.scheduling.schedulers.Two    : second one
2021-07-26 08:04:03.479  INFO 91877 --- [led-task-pool-1] com.example.scheduling.schedulers.One    : first one
2021-07-26 08:04:03.479  INFO 91877 --- [led-task-pool-3] com.example.scheduling.schedulers.Three  : third one

Reference:

  1. https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/EnableScheduling.html