技术交流QQ群
933925017
Springboot配置多线程定时任务Scheduled springboot默认定时任务是单线程的,需要配置成多线程
一.为什么需要配置多线程定时任务& 多线程定时任务的配置使用场景
springboot中通过注解 @Scheduled 注解的方法都是一个定时执行的任务, 默认都是单线程的,就算是多个定时任务也是在同一个单线程(scheduled-1)中运行, 如果其中某一个定时任务产生了阻塞,那么会导致项目中其他所有的定时任务线程都不执行。后果非常严重,故而需要配置多线程定时任务。
2.多线程定时任务配置类
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;
@Configuration
@EnableScheduling // 开启定时任务
public class ScheduledConfiguration implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix("scheduled@");// 设置定时任务线程名称的前缀
int corePoolSize = 10; // 设置定时任务的核心线程数
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(corePoolSize,executor));
}
}
3.测试
// 定时任务1,用于测试
@Scheduled(fixedDelay = 1000)
public void test1() throws IOException {
Thread thread = Thread.currentThread();
log.info("test1定时任务处理线程 : "+thread.getName());
}
// 定时任务2,用于测试
@Scheduled(fixedDelay =1000)
public void test2() throws IOException {
Thread thread = Thread.currentThread();
log.info("test2定时任务处理线程开始休眠 : "+thread.getName());
try {
Thread.sleep(100000000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}