update ,解决同步问题可能造成的定时任务未按规定执行的问题

This commit is contained in:
yyb
2026-01-06 13:54:23 +08:00
parent 5559163b2e
commit b622701e39
5 changed files with 98 additions and 25 deletions

View File

@@ -2,11 +2,14 @@ package com.m2pool.lease.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class ThreadPoolConfig {
@Bean(name = "customThreadPool")
@@ -28,4 +31,48 @@ public class ThreadPoolConfig {
executor.initialize();
return executor;
}
/**
* 定时任务专用线程池
* 用于解决多个定时任务同时执行时相互影响导致执行时间不固定的问题
*/
@Bean(name = "scheduledTaskExecutor")
public ThreadPoolTaskExecutor scheduledTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程数,设置为定时任务的数量,确保每个任务都有独立的线程
executor.setCorePoolSize(10);
// 最大线程数
executor.setMaxPoolSize(20);
// 队列容量设置为0让任务直接进入线程池执行避免排队等待
executor.setQueueCapacity(0);
// 线程空闲时间(秒)
executor.setKeepAliveSeconds(60);
// 线程名前缀
executor.setThreadNamePrefix("scheduled-task-");
// 拒绝策略:由调用者线程执行(主线程),确保任务不会丢失
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 允许核心线程超时
executor.setAllowCoreThreadTimeOut(true);
// 初始化
executor.initialize();
return executor;
}
/**
* 异步任务执行器配置
*/
@Bean(name = "asyncTaskExecutor")
public AsyncTaskExecutor asyncTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(15);
executor.setQueueCapacity(100);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("async-task-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
executor.initialize();
return executor;
}
}