package cn.superdesk.uniorder.common.queue.delayed;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Executors;

/**
 * @Description: 延时队列管理-原生实现
 * @Author: linjinyu
 * @CreateDate: 9/21/20 3:16 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 9/21/20 3:16 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */

@Slf4j
public abstract class DelayQueueManager implements CommandLineRunner {

	private DelayQueue<DelayTaskAsync> delayQueue = new DelayQueue<>();


	/**
	 * 延时任务执行线程
	 */
	private void excuteThread() {

		while (true) {
			try {
				DelayTaskAsync task = delayQueue.take();
				processTask(task);
			} catch (InterruptedException e) {
				break;
			}
		}
	}

	protected abstract void processTask(DelayTaskAsync taskAsync);

	/**
	 * 加入到延时队列中
	 *
	 * @param task
	 */
	public void put(DelayTaskAsync task) {
		log.error("加入延时任务:{}", task);
		delayQueue.put(task);
	}

	/**
	 * 取消延时任务
	 *
	 * @param task
	 * @return
	 */
	public boolean remove(DelayTaskAsync task) {
		log.error("取消延时任务:{}", task);
		return delayQueue.remove(task);
	}

	/**
	 * 取消延时任务
	 *
	 * @param taskId
	 * @return
	 */
	public boolean remove(String taskId) {
		return remove(new DelayTaskAsync(new DelayTaskBase(taskId), 0));
	}

	@Override
	public void run(String... args) throws Exception {

		log.info("初始化延时队列 {}", args);

		Executors.newSingleThreadExecutor().execute(new Thread(this::excuteThread));
	}

}
