Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does spring @Scheduled annotated methods runs on different threads?

I have several methods annotated with @Scheduled(fixedDelay=10000).

In the application context, I have this annotation-driven setup:

<task:annotation-driven /> 

The problem is, sometimes some of the method executions get delayed by seconds and even minutes.

I'm assuming that even if a method takes a while to finish executing, the other methods would still execute. So I don't understand the delay.

Is there a way to maybe lessen or even remove the delay?

like image 809
froi Avatar asked Feb 24 '14 16:02

froi


People also ask

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.

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.

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.

What is @scheduled in Java?

The schedule (TimerTask task, Date time) method of Timer class is used to schedule the task for execution at the given time. If the time given is in the past, the task is scheduled at that movement for execution.


2 Answers

The documentation about scheduling says:

If you do not provide a pool-size attribute, the default thread pool will only have a single thread.

So if you have many scheduled tasks, you should configure the scheduler, as explained in the documentation, to have a pool with more threads, to make sure one long task doesn't delay all the other ones.

like image 136
JB Nizet Avatar answered Sep 18 '22 05:09

JB Nizet


For completeness, code below shows the simplest possible way to configure scheduler with java config:

@Configuration @EnableScheduling public class SpringConfiguration {      @Bean(destroyMethod = "shutdown")     public Executor taskScheduler() {         return Executors.newScheduledThreadPool(5);     }     ... 

When more control is desired, a @Configuration class may implement SchedulingConfigurer.

like image 43
G. Demecki Avatar answered Sep 20 '22 05:09

G. Demecki