定时任务里面的任务多线程操作

75 阅读1分钟
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import java.util.concurrent.*;
@Configuration
@EnableAsync
public class AsyncConfig2 {
    //获取cpu数,但是好像不准
    private static final int NTHREADS = Runtime.getRuntime().availableProcessors();
    private static ThreadFactory SENDE_FACTORY = new ThreadFactoryBuilder()
            .setNameFormat("send-pool-%d").build();
    
    @Bean
    public Executor taskExecutor() {
        ExecutorService sendEmailForM3MerchanthreadPool = new ThreadPoolExecutor(NTHREADS * 2, NTHREADS * 2, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000),SEND_FACTORY );
        return sendMerchanthreadPool;
    }
}

或者

@Configuration
@EnableAsync
public class AsyncConfig implements SchedulingConfigurer {
    /**
     * 获取cpu数
     */
    private static final int NTHREADS = Runtime.getRuntime().availableProcessors();
    /**
     * 定义线程工厂名称
     */
    private static ThreadFactory HANDLEREMINDWAY_FACTORY = new ThreadFactoryBuilder()
            .setNameFormat("handleRemindWay-pool-%d").build();
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(NTHREADS * 2, HANDLEREMINDWAY_FACTORY));
    }
}

1、定义定时任务,添加@EnableAsync开启对异步的支持
2、在springboot启动类加上注解

@EnableScheduling

3、在使用的地方定义

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
@EnableScheduling
public class Send {
    private final static Logger log = LoggerFactory.getLogger(Send.class);
    @Async
    @Scheduled(cron = "0/1 * * * * ?")
    public void doBiz() {
        log.info("定时任务开始 :{} " + "\r\n线程 : {}", LocalDateTime.now().toLocalTime(), Thread.currentThread().getName());
    }
}

指定多个线程池的方式:
或者配置多个线程池

@Configuration
@EnableAsync
public class ExecutorConfig1 {
 @Bean
 public Executor executor1() {
  ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  executor.setThreadNamePrefix("test-schedule1-");
  executor.setMaxPoolSize(20);
  executor.setCorePoolSize(15);
  executor.setQueueCapacity(0);
  executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  return executor;
 }
 
 @Bean
 public Executor executor2() {
  ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  executor.setThreadNamePrefix("test-schedule2-");
  executor.setMaxPoolSize(20);
  executor.setCorePoolSize(15);
  executor.setQueueCapacity(0);
  executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  return executor;
  }
}

使用

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
@EnableScheduling
public class Send {
    private final static Logger log = LoggerFactory.getLogger(Send.class);
    @Async("executor2")
    @Scheduled(cron = "0/1 * * * * ?")
    public void doBiz() {
        log.info("定时任务开始 :{} " + "\r\n线程 : {}", LocalDateTime.now().toLocalTime(), Thread.currentThread().getName());
    }
}