package com.iamberry.wechat.handles.mq;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

import com.iamberry.app.tool.log.RatFWLogger;
import com.iamberry.wechat.core.entity.mq.MQMessage;
import com.iamberry.wechat.face.mq.MQSerivce;

public class MQTimer extends TimerTask {

	// 队列
	public static BlockingQueue<MQMessage> messageStaticQueue = new ArrayBlockingQueue<MQMessage>(500);
	
	private MQSerivce mQSerivce;
	
	private RatFWLogger ratFWLogger;
	
	public MQTimer(MQSerivce mqSerivce, RatFWLogger logger) {
		this.mQSerivce = mqSerivce;
		this.ratFWLogger = logger;
	}

	@Override
	public void run() {
		ratFWLogger.info("启动订阅程序...");
		// 订阅
		try {
			while (true) {
				// 如果空闲，阻塞，让出系统资源
				MQMessage mqMessage = messageStaticQueue.take();
				ratFWLogger.info("收到订阅请求...");
				// 远程调用 Service
				boolean flag = mQSerivce.updateMessageOne(mqMessage);
				if (flag) {
					ratFWLogger.info(mqMessage + "   execution true");
				} else {
					ratFWLogger.error(this, mqMessage + "   execution error");
				}
			}
		} catch (Exception e) {
			ratFWLogger.error(this, e.getMessage());
			new Timer().schedule(new MQTimer(mQSerivce, ratFWLogger), 1000);
		}
	}

}
