package com.xixun.communicate.Task;

import com.xixun.display.MyLog;

import java.util.concurrent.ConcurrentHashMap;


public class PollingWorker extends Thread {
	private static final ConcurrentHashMap<Worker, PollingWorker> pollingWorkers = new ConcurrentHashMap<Worker, PollingWorker>();
	
	private Worker worker;
	private long delay;
	private long interval;
	
	public Worker getWorker() {
		return worker;
	}
	
	/**
	 * 添加一个任务
	 * @param delay: 延迟多久开始执行
	 * @param interval：间隔时间
	 * @param worker
	 */
	public void addWorker(long delay, long interval, Worker worker) {
		this.delay = delay;
		this.interval = interval;
		this.worker = worker;
		if ("".equals(worker.getName())) {
			worker.setName("Worker$" + (pollingWorkers.size() + 1));
		}
		if (null == pollingWorkers.putIfAbsent(worker, this)) {
			this.start();
			MyLog.i("Hire worker ==> " + worker.getName());
		}
	}
	
	/**
	 * 移除一个任务
	 * @param worker
	 */
	public static void fireWorker(Worker worker) {
		synchronized(pollingWorkers) {
			if (pollingWorkers.containsKey(worker)) {
				PollingWorker pollingWorker = pollingWorkers.get(worker);
				pollingWorkers.remove(worker);
				pollingWorker.interrupt();
				MyLog.i("Fire worker ==> " + worker.getName());
			}
		}
	}
	
	@Override
	public void run() {
		try {
			if (delay > 0) {
				Thread.sleep(delay);
			}
			while (!isInterrupted()) {
				worker.exec();
				// 轮寻任务至少间隔10ms，防止出现死循环
				Thread.sleep((interval > 10) ? interval: 10);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
			interrupt();
		}
	}
}
