0
spring定时任务@Scheduler默认为单线程模式,并且任务队列为无限大的(自动扩容机制)。单线程模式的缺点和任务队列的扩容机制可参考之前我写的 spring定时任务Scheduled注解源码分析 这篇文章是如何扩容的。
第一种方式(实现SchedulingConfigurer接口):
package com.lds.springbootdemo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import java.util.concurrent.Executor; import java.util.concurrent.Executors; @Configuration public class ScheduledConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) { scheduledTaskRegistrar.setScheduler(setTaskExecutors()); } @Bean(destroyMethod="shutdown") public Executor setTaskExecutors(){ // 10个线程来处理。 return Executors.newScheduledThreadPool(10); } }
第二种方式(创建Bean):
@Bean public TaskScheduler taskScheduler() { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setPoolSize(10); return scheduler; }
0
一条评论 “spring定时任务设置为多线程执行的两种方式(来源网络)”
Nice read mate, good to see some of us have a life outside of work. Lucina Norman Bound Chloette Dickie Farlie