package com.zhiwei.manage.handle;

import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

import com.zhiwei.manage.bean.PingUrl;
import com.zhiwei.manage.util.Tools;

@Component
public class PingThread extends Thread {

	private static boolean isrun = true;
	public static Map<String, PingUrl> runMap = new ConcurrentHashMap<String, PingUrl>();
	public static Queue<PingUrl> queue = new LinkedBlockingQueue<PingUrl>(500);
	private static Lock pingLock = new ReentrantLock();
	private static final Log log = LogFactory.getLog(PingThread.class);

	public PingThread() {
		this.start();
	}

	public void stopMe() {
		isrun = false;
	}

	@Override
	public void run() {
		log.info("ping线程启动");
		while (isrun) {
			try {
				pingLock.lock();
				Set<String> keys = runMap.keySet();
				for (Iterator<String> it = keys.iterator(); it.hasNext();) {
					String key = it.next();
					PingUrl run = runMap.get(key);
					Calendar cal = Calendar.getInstance();
					if (run.getNextRun().before(cal.getTime())) {
						System.out.println("ping添加一个");
						queue.offer(run);
						cal.add(Calendar.HOUR, run.getPingInterval());
						run.setNextRun(cal.getTime());
					}
				}
			} catch (Exception e) {
				log.info("ping线程错误信息{}", e);
			} finally {
				pingLock.unlock();
			}
			Tools.sleep(1000);
		}
	}
}
