package org.xyzh.message.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executor;

/**
 * 定时任务和异步任务配置类
 *
 * @description 配置消息模块的定时任务线程池和异步任务线程池
 * @filename SchedulingConfig.java
 * @author Claude
 * @copyright xyzh
 * @since 2025-11-13
 */
@Configuration
@EnableAsync
public class SchedulingConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(messageSchedulerExecutor());
    }

    @Bean(name = "messageSchedulerExecutor")
    public TaskScheduler messageSchedulerExecutor() {
        ThreadPoolTaskScheduler executor = new ThreadPoolTaskScheduler();
        // 线程池大小：5个线程用于定时任务扫描
        executor.setPoolSize(5);
        // 线程名称前缀
        executor.setThreadNamePrefix("message-scheduler-");
        // 等待所有任务完成后再关闭
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时间（秒）
        executor.setAwaitTerminationSeconds(60);
        // 初始化
        executor.initialize();
        return executor;
    }

    /**
     * 异步任务线程池配置
     */
    @Bean(name = "messageAsyncExecutor")
    public Executor messageAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数：10个线程用于异步发送消息
        executor.setCorePoolSize(10);
        // 最大线程数
        executor.setMaxPoolSize(20);
        // 队列容量
        executor.setQueueCapacity(500);
        // 线程名称前缀
        executor.setThreadNamePrefix("message-async-");
        // 等待所有任务完成后再关闭
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 等待时间（秒）
        executor.setAwaitTerminationSeconds(60);
        // 初始化
        executor.initialize();
        return executor;
    }
}
