繁体   English   中英

spring-boot 中的默认调度程序池大小是多少?

[英]What is the default scheduler pool size in spring-boot?

我正在使用spring-boot@Scheduled注释来执行一些任务。

如何在 spring-boot 中找出默认情况下计划任务的默认池大小是多少?

原因:下面的类不是并行执行作业,而是一个接一个地执行。 也许默认只配置了一个单线程执行器?

@Service
public class ZipFileTesterAsync {

    @Scheduled(fixedDelay = 60000, initialDelay = 500)
    public void run() throws Exception {
        System.out.println("import 1");
        TimeUnit.MINUTES.sleep(1);
        System.out.println("import 1 finished");
    }

    @Scheduled(fixedDelay = 60000, initialDelay = 1000)
    public void run2() throws Exception {
        System.out.println("import 2");
        TimeUnit.MINUTES.sleep(1);
    }
}

结果:第一个作业完成后执行第二个作业。

是的,所有@Scheduled方法默认共享一个线程。 可以通过定义@Configuration来覆盖此行为,例如:

@Configuration
public class SchedulingConfigurerConfiguration implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
        taskScheduler.setPoolSize(100);
        taskScheduler.initialize();
        taskRegistrar.setTaskScheduler(taskScheduler);
    }
}

此示例确保所有@Scheduled方法共享大小为 100 的线程池。

默认池大小为 1,您可以在application.properties science springboot2.1.0 中通过更改spring.task.scheduling.pool.size的值来设置池大小。

spring.task.scheduling.pool.size=20

当触发周期小于执行持续时间时,相同的任务将被串行执行。 并且 Spring Boot 会以最多 20 个线程并行执行不同的任务。

spring-boot 中的默认调度程序池大小仅为 1

org.springframework.scheduling.config.ScheduledTaskRegistrar

    /**
     * Schedule all registered tasks against the underlying
     * {@linkplain #setTaskScheduler(TaskScheduler) task scheduler}.
     */
    @SuppressWarnings("deprecation")
    protected void scheduleTasks() {
        if (this.taskScheduler == null) {
            this.localExecutor = Executors.newSingleThreadScheduledExecutor();
            this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);
        }
        ...
    }

一个非常简单的方法来做到这一点:

@Configuration
public class ScheduleConfig {
  ScheduleConfig(ThreadPoolTaskScheduler threadPoolTaskScheduler) {
    threadPoolTaskScheduler.setPoolSize(10);
  }
}

使用内置功能和带注释的弹簧配置,这将是这样的:

    @Bean
    public TaskScheduler taskScheduler() {
        return new ConcurrentTaskScheduler(new ScheduledThreadPoolExecutor(20));
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM