spring mvc定时任务实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_16855077/article/details/84548814

1.pom.xml

<properties>
    <quartz-version>2.2.1</quartz-version>
</properties>
<!-- quartz -->
		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz</artifactId>
			<version>${quartz-version}</version>
		</dependency>
		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz-jobs</artifactId>
			<version>${quartz-version}</version>
		</dependency>

 2.JobScheduler

package com.parwa.rc.comm.quarz;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;


/**
 * 
 * @describe  定时任务初始化类
 * @author wude
 * @date 2017年2月7日
 * @see JobScheduler
 */
public abstract class JobScheduler {


    public static Scheduler scheduler ;

    /**
     * 启动定时任务
     * 
     * @throws SchedulerException
     */
    public synchronized void startScheduler() throws SchedulerException {
        if (scheduler == null) {
            SchedulerFactory schedulerFactory = new StdSchedulerFactory();
            scheduler = schedulerFactory.getScheduler();
            scheduler.start();
        }
    }

    /**
     * 停止定时任务
     * 
     * @throws SchedulerException
     */
    public synchronized void stopScheduler() throws SchedulerException {
        if (scheduler != null) {
            scheduler.shutdown(false);
            scheduler = null;
        }
    }

}

3.job

package com.parwa.rc.comm.quarz;

import java.util.Date;

import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.parwa.rc.comm.module.facade.MachineFacade;
import com.parwa.web.dubbo.DubboService;

/**
 * 
 * @describe 消息重发scheduler
 * 
 * @author wude
 * 
 * @date 2016年11月22日
 * 
 * @see RuleDetectionScheduler
 */
@Component("msgResendScheduler")
public class MsgResendScheduler extends JobScheduler {
	private static final Logger LOGGER = LoggerFactory.getLogger(MsgResendScheduler.class);

	@Autowired
	private MachineFacade machineFacade;
	@Autowired
	private DubboService dubboService;

	
	/**
	 * 增加job  消息重发
	 */
	public void addJob() {
		// 加载所有状态为启动的计算单元规则
		LOGGER.info("初始化加载消息重发job");
		try {
			super.startScheduler();
			// 拼接job名称 格式RuleDetectionJob+规则从表id 保证唯一
			String name = "MsgResendJob";
			Trigger trig = checkTrigger(name);
			if (null == trig) {
				JobDetail jobDetail = JobBuilder.newJob(MsgResendJob.class).build();
				JobDataMap jobDataMap = jobDetail.getJobDataMap();
				jobDataMap.put("machineFacade", machineFacade); 
				jobDataMap.put("dubboService", dubboService); 
				// 时间间隔
				int intervalInSeconds = 1;
				// 运行次数  
				int withRepeatCount = Integer.MAX_VALUE;
				// 循环次数 三个月有2592000s
				SimpleTrigger trigger = (SimpleTrigger) TriggerBuilder.newTrigger().withIdentity(name, name)
						.withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(intervalInSeconds)
								.withRepeatCount(withRepeatCount))
						.build();
				Date ft = scheduler.scheduleJob(jobDetail, trigger);
				LOGGER.info(name + "触发时间:" + ft.toLocaleString());
			}
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}
	
	/** Description:验证Trigger是否存在
	 *  @author wude 
	 *  @param name 
	 *  @return 
	 *  @throws SchedulerException 
	 *  @date 2016年11月24日 */ 
	public static Trigger checkTrigger(String name) throws SchedulerException { 
		final TriggerKey triggerKey = TriggerKey.triggerKey(name, name);
		Trigger trig = scheduler.getTrigger(triggerKey); 
		return trig; 
	}
}
package com.parwa.rc.comm.quarz;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.parwa.rc.comm.enums.SendCmdType;
import com.parwa.rc.comm.module.facade.MachineFacade;
import com.parwa.rc.comm.module.model.CommandCache;
import com.parwa.rc.comm.module.model.CommandCallBack;
import com.parwa.web.dubbo.DubboService;
import com.parwa.web.entity.Pile;

/**
 * 自定义规则检测job
 * 
 * @describe
 * @author wude
 * @date 2016年11月22日
 * @see RulesDetectionJob
 */
public class MsgResendJob implements Job {
	private static final Logger LOGGER = LoggerFactory.getLogger(MsgResendJob.class);
	
	private MachineFacade machineFacade;
	private DubboService dubboService;

	@Override
	public void execute(JobExecutionContext content) throws JobExecutionException {
		init(content);

		for (CommandCache commandCache : machineFacade.CMD_MAP.values()) {
			if (commandCache.isOverTime() == false) {
				// 发送超时
				continue;
			}
			CommandCallBack callBack = commandCache.getCallBack();
			if (commandCache.isOverCount()) {
				// 重发次数超限
				machineFacade.CMD_MAP.remove(commandCache.getMsgNumber());
				if (LOGGER.isDebugEnabled()) {
					LOGGER.debug("命令重发次数超限:{}", commandCache);
				}
				if (callBack != null) {
					callBack.doFail();
				}
				continue;
			}
			machineFacade.CMD_MAP.remove(commandCache.getMsgNumber());
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("命令重发:{}", commandCache);
			}
			
			if(commandCache.isSendCommand()){
				SendCmdType sendCmdType = SendCmdType.getType(commandCache.getCommandType());
				switch (sendCmdType) {
				case OLD_REMOTE_CONTROL:
					machineFacade.sendCommand(commandCache.getPileNum(), commandCache.getOldCommand(), commandCache.getSendCount(), callBack);
					break;
				case NEW_REMOTE_CONTROL:
					machineFacade.sendCommand(commandCache.getPileNum(), commandCache.getCommand(), commandCache.getSendCount(), callBack);
					break;
				 case NEW_REMOTE_UPGRADE:
					 machineFacade.sendCommand(commandCache.getPileNum(), commandCache.getUpgradeCommand(), commandCache.getSendCount(), callBack);	
					break;
				case NEW_PARAM_SET:
					 machineFacade.sendCommand(commandCache.getPileNum(), commandCache.getParamSetResponse(), commandCache.getSendCount(), callBack);		
					break;
				case NEW_PARAM_READ:
					 machineFacade.sendCommand(commandCache.getPileNum(), commandCache.getParamReadResponse(), commandCache.getSendCount(), callBack);		
					break;
				}
			}
		}
	}

	private void init(JobExecutionContext context) {
		machineFacade = (MachineFacade) context.getJobDetail().getJobDataMap().get("machineFacade");
		dubboService = (DubboService) context.getJobDetail().getJobDataMap().get("dubboService");
	}
}

猜你喜欢

转载自blog.csdn.net/qq_16855077/article/details/84548814