Commit b726dc97538b7d4ba71fd06c14161017dd67c2b7

Authored by xubinbin
1 parent ccecda78

"@schedule"是Spring框架提供的一种定时任务执行机制,默认情况下它是单线程执行,项目中多次使用fixedRate按指定频率执行任务(不管前面任务是…

…否已经完成),在同时执行多个定时任务时可能会出现阻塞和性能问题,为了解决这种单线程瓶颈问题,将定时任务的执行机制改为支持多线程
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 +}
... ...