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 org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

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

@Component
public class DelayedThread extends Thread {

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

	public DelayedThread(){
		this.start();
	}
	
	public void stopMe() {
		isrun = false;
	}

	@Override
	public void run() {
		log.info("字段检测开启");
		while (isrun) {
			Set<String> keys = runMap.keySet();
			for (Iterator<String> it = keys.iterator(); it.hasNext();) {
				String key = it.next();
				NewsDelayed run = runMap.get(key);
				Calendar cal = Calendar.getInstance();
				if (run.getNextRun().before(cal.getTime())&&!run.isStartNow()) {
					queue.offer(run);
					cal.add(Calendar.HOUR, run.getDelayedInterval());
					run.setNextRun(cal.getTime());
				}
			}
			Tools.sleep(1000);
		}
	}
}
