package com.bohuikeji.frame.module.admin.task;


import com.bohuikeji.frame.module.admin.thread.CachedThreadPool;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.concurrent.DelayQueue;

/**
 * 延时队列控制器
 * @author ：孙劲辉
 * @date ：Created in 2021/6/29 8:06
 * @description：延时任务队列
 * @modified By：
 * @version: $
 */
@Slf4j
public class TaskQueue {

    /**
     * 延时队列
     */
    private static final DelayQueue<TaskDelayed> DELAY_QUEUE;
    /**
     * 守护线程
     */
    private static final Thread DAMON;


    /**
     * 初始化
     */
    static {
        DELAY_QUEUE=new DelayQueue<TaskDelayed>();
        /**
         * 启动守护线程
         */
        DAMON = new Thread(TaskQueue::execute);
        DAMON.setDaemon(true);
        DAMON.setName("Delayed Task Damon Thread");
        DAMON.start();
    }

    /**
     * 执行任务
     */
    private static void execute(){
        while (true){
            try {
                TaskDelayed taskDelayed=DELAY_QUEUE.take();
                CachedThreadPool.execute(() -> taskDelayed.getTask().runTask(taskDelayed.getParams()));
            } catch (Exception e) {
                log.error("【延时任务执行错误】，异常信息：",e);
                e.printStackTrace();
            }
        }
    }

    /**
     * 插入任务元素
     * @param taskDelayed 任务控制体
     * @return 返回唯一任务id，此id用于后续的查询，移除任务等
     */
    public static TaskDelayed put(TaskDelayed taskDelayed){
        DELAY_QUEUE.put(taskDelayed);
        return taskDelayed;
    }

    /**
     * 移除任务元素
     * @param taskDelayed
     * @return
     */
    public static boolean remove(TaskDelayed taskDelayed){
        return DELAY_QUEUE.remove(taskDelayed);
    }

}
