Does spring @Scheduled annotated methods runs on different threads?

前端 未结 8 2237
时光取名叫无心
时光取名叫无心 2020-11-30 01:19

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

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

<         


        
相关标签:
8条回答
  • 2020-11-30 01:22

    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.

    0 讨论(0)
  • 2020-11-30 01:28

    Using XML file add below lines..

    <task:scheduler id="taskScheduler" pool-size="15" />
    <task:scheduled-tasks scheduler="taskScheduler" >
    ....
    </task:scheduled-tasks>
    
    0 讨论(0)
  • 2020-11-30 01:29

    UPDATE 2019

    There is also a property you can set in your application properties file that increases the pool size:

    spring.task.scheduling.pool.size=10

    Seems to be there since Spring Boot 2.1.0.

    0 讨论(0)
  • 2020-11-30 01:30

    you can use:

    @Bean()
    public  ThreadPoolTaskScheduler  taskScheduler(){
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(2);
        return  taskScheduler;
    }
    
    0 讨论(0)
  • 2020-11-30 01:32

    A method annotated with @Scheduled is meant to be run separately, on a different thread at a moment in time.

    If you haven't provided a TaskScheduler in your configuration, Spring will use

    Executors.newSingleThreadScheduledExecutor();
    

    which returns an ScheduledExecutorService that runs on a single thread. As such, if you have multiple @Scheduled methods, although they are scheduled, they each need to wait for the thread to complete executing the previous task. You might keep getting bigger and bigger delays as the the queue fills up faster than it empties out.

    Make sure you configure your scheduling environment with an appropriate amount of threads.

    0 讨论(0)
  • 2020-11-30 01:33

    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.

    0 讨论(0)
提交回复
热议问题