Commit 512b0cc8f5606f08b93afb154f0cffd92b93cac8

Authored by 648540858
Committed by GitHub
2 parents cf48bd95 b726dc97

Merge pull request #847 from xu-bin-bin/wvp-28181-2.0

"@schedule"是Spring框架提供的一种定时任务执行机制,默认情况下它是单线程执行,将其修改为支持多线程。
src/main/java/com/genersoft/iot/vmp/conf/ScheduleConfig.java 0 → 100644
  1 +package com.genersoft.iot.vmp.conf;
  2 +
  3 +import org.apache.commons.lang3.concurrent.BasicThreadFactory;
  4 +import org.springframework.context.annotation.Configuration;
  5 +import org.springframework.scheduling.annotation.SchedulingConfigurer;
  6 +import org.springframework.scheduling.config.ScheduledTaskRegistrar;
  7 +
  8 +import java.util.concurrent.ScheduledThreadPoolExecutor;
  9 +import java.util.concurrent.ThreadPoolExecutor;
  10 +
  11 +/**
  12 + * "@Scheduled"是Spring框架提供的一种定时任务执行机制,默认情况下它是单线程的,在同时执行多个定时任务时可能会出现阻塞和性能问题。
  13 + * 为了解决这种单线程瓶颈问题,可以将定时任务的执行机制改为支持多线程
  14 + */
  15 +@Configuration
  16 +public class ScheduleConfig implements SchedulingConfigurer {
  17 +
  18 + public static final int cpuNum = Runtime.getRuntime().availableProcessors();
  19 +
  20 + private static final int corePoolSize = cpuNum;
  21 +
  22 + private static final String threadNamePrefix = "scheduled-task-pool-%d";
  23 +
  24 + @Override
  25 + public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
  26 + taskRegistrar.setScheduler(new ScheduledThreadPoolExecutor(corePoolSize,
  27 + new BasicThreadFactory.Builder().namingPattern(threadNamePrefix).daemon(true).build(),
  28 + new ThreadPoolExecutor.CallerRunsPolicy()));
  29 + }
  30 +}
... ...