SpringBoot@Scheduled注解配置

一、话不多说,上代码

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

@EnableScheduling
@Configuration
public class LianScheduleConfig implements SchedulingConfigurer {

    /*获取当前系统的CPU数,根据CPU数初始化线程*/
    private static final int PROCESSORS_COUNT = Runtime.getRuntime().availableProcessors();

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        // <核心线程数>线程池创建时候初始化的线程数
        threadPool.setCorePoolSize(PROCESSORS_COUNT);
        // <最大线程数>线程池最大的线程数,只有在<缓冲队列数>满了之后才会申请超过核心线程数的线程
        threadPool.setMaxPoolSize(PROCESSORS_COUNT * 2);
        // <缓冲队列数>线程池所使用的缓冲队列
        threadPool.setQueueCapacity(PROCESSORS_COUNT * 10);
        // 当线程数超过最大线程数时,处理方式
        // new ThreadPoolExecutor.AbortPolicy():丢弃任务并抛出RejectedExecutionException异常
        // new ThreadPoolExecutor.DiscardPolicy():也是丢弃任务,但是不抛出异常
        // new ThreadPoolExecutor.DiscardOldestPolicy():丢弃<缓冲队列数>最前面的任务,然后重新尝试执行任务
        // new ThreadPoolExecutor.CallerRunsPolicy():由调用线程处理该任务,一般会阻塞,说白了就是没有线程作用~
        threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // <核心线程数>之外的线程在空闲时间60秒到达之后会被销毁
        threadPool.setKeepAliveSeconds(60);
        // <核心线程数>之外的线程在存活时间10分钟到达之后会被销毁
        threadPool.setAwaitTerminationSeconds(10 * 60);
        // 线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean,这样这些异步任务的销毁就会先于Redis线程池的销毁。
        threadPool.setWaitForTasksToCompleteOnShutdown(true);
        // 线程前缀
        threadPool.setThreadNamePrefix("LianScheduled-");

        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(PROCESSORS_COUNT, threadPool));
    }
}

二、为什么要配置?

1、@Scheduled默认不配置的时候是使用单线程处理,比如你有两个方法A和B使用定时任务@Scheduled注解,那么在运行时,A方法执行完毕后,才会执行B方法,也就是如果A方法在执行的时候堵塞了,B方法就不会执行~

三、@Scheduled参数说明参考https://www.jianshu.com/p/1defb0f22ed1

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章