package com.mes.tools;
|
|
import org.springframework.context.annotation.Configuration;
|
import org.springframework.scheduling.annotation.SchedulingConfigurer;
|
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
|
|
import java.util.concurrent.*;
|
import java.util.concurrent.atomic.AtomicInteger;
|
|
/**
|
* @author huang
|
* @since 2025/10/22
|
*/
|
@Configuration
|
public class SchedulerConfig implements SchedulingConfigurer {
|
|
@Override
|
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
|
// 使用 ScheduledThreadPoolExecutor(支持定时调度的线程池)
|
ScheduledThreadPoolExecutor schedulerPool = new ScheduledThreadPoolExecutor(
|
// 核心线程数:根据定时任务数量设置
|
5,
|
new ThreadFactory() {
|
private final AtomicInteger count = new AtomicInteger(1);
|
@Override
|
public Thread newThread(Runnable r) {
|
return new Thread(r, "scheduler-thread-" + count.getAndIncrement());
|
}
|
},
|
new ThreadPoolExecutor.CallerRunsPolicy()
|
);
|
// 设置空闲线程存活时间(非核心线程,默认60秒,可按需调整)
|
schedulerPool.setKeepAliveTime(60, TimeUnit.SECONDS);
|
// 允许核心线程超时销毁(如果任务不频繁,可节省资源)
|
schedulerPool.allowCoreThreadTimeOut(true);
|
|
taskRegistrar.setScheduler(schedulerPool);
|
}
|
}
|