package com.njzscloud.common.sichen.executor;

import com.njzscloud.common.core.thread.ThreadPool;
import com.njzscloud.common.sichen.contant.TaskStatus;
import com.njzscloud.common.sichen.support.TaskHandle;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
public class SichenExecutor {

    private final ThreadPoolExecutor taskThreadPool;

    public SichenExecutor(ThreadPoolExecutor taskThreadPool) {
        log.info("任务执行器启动中...");
        this.taskThreadPool = taskThreadPool;
        log.info("任务执行器已启动");
    }

    public SichenExecutor() {
        this(ThreadPool.createThreadPool("任务执行器",
                10, 200,
                300,
                20, 8192,
                (r, p) -> log.error("任务执行器线程池已满，拒绝任务：{}", r.toString())));
    }

    public void execute(TaskHandle taskHandle) {
        if (taskHandle.getStatus() != TaskStatus.Waiting) {
            return;
        }
        taskHandle.setStatus(TaskStatus.Pending);
        taskThreadPool.execute(taskHandle);
    }

    public void stop() {
        log.info("正在停止任务执行器...");
        taskThreadPool.shutdownNow();
        log.info("任务执行器已停止");
    }

}
