Bootstrap

org.quartz调度JOB执行时间超过调度周期的情况说明

使用quartz时,如果JOB执行时间,大于cron的设定的时间周期,遇到这种情况一般怎么办呢?

如果你的JOB任务类是现实org.quartz.StatefulJob接口,则只能等前一个任务执行完。

如果你的JOB任务类实现org.quartz.Job接口,那么默认不处理的话,上个Job执行继续,容器又会重启一个新的Job,出现并发的情况。

当然可以人为判断,让容器中存在几个任务。比如:

JOB实现类

	public void execute(JobExecutionContext context)
			throws JobExecutionException {
		Scheduler sched = context.getScheduler();
		JobDetail jobDetail;
		String groupName = null;
		String jobName = null;
		try {
			jobDetail = sched.getJobDetail(ScheduleTask.JOB_DETAIL_NAME, Scheduler.DEFAULT_GROUP);
			groupName = jobDetail.getGroup();
			jobName = jobDetail.getName();
			boolean isContainJob = ScheduleDataCache.getInstance().isContainScheduleJob(groupName, jobName);
			if(isContainJob){
				long lastJobTime = ScheduleDataCache.getInstance().getJobExeTime(groupName, jobName);
				logger.info("上一个Job("+new Date(lastJobTime)+")还未执行完成,本次新线程Job,从execute方法直接退出");
				return;
			} else {
				ScheduleDataCache.getInstance().addScheduleJob(groupName, jobName, System.currentTimeMillis());
			}
		} catch (SchedulerException e) {
			logger.error(e, e);
		}		
		ProbeProcessor.getInstance().exploreWaitingTask();
		logger.info("本次Job任务结束");
		if(groupName != null && jobName != null){
			ScheduleDataCache.getInstance().removeScheduleJob(groupName, jobName);
		}
	}


ScheduleDataCache类

public class ScheduleDataCache {
	
	private static ScheduleDataCache instance = new ScheduleDataCache();;
	
	/** 缓存执行任务<"任务唯一标识","任务执行时间">*/
	private Map<String,Long> scheduleJobMap = new HashMap<String,Long>();
	
	private ScheduleDataCache(){
	}
	
	public static ScheduleDataCache getInstance() {
		return instance;
	}
	
	/**
	 * 获取任务唯一标识
	 * @param groupName
	 * @param jobName
	 * @return
	 */
	public static String getKey(String groupName,String jobName){
		return groupName+"-"+jobName;
	}
	
	/**
	 * 是否包含Job
	 * @param groupName
	 * @param jobName
	 * @return
	 */
	public boolean isContainScheduleJob(String groupName,String jobName){
		return scheduleJobMap.containsKey(getKey(groupName, jobName));
	}
	
	/**
	 * get Job exe time
	 * @param groupName
	 * @param jobName
	 */
	public long getJobExeTime(String groupName,String jobName){
		return scheduleJobMap.get(getKey(groupName, jobName));
	}
	
	/**
	 * add Job
	 * @param groupName
	 * @param jobName
	 * @param timeMills
	 */
	public void addScheduleJob(String groupName,String jobName,long timeMills){
		scheduleJobMap.put(getKey(groupName, jobName),timeMills);
	}
	
	/**
	 * 删除Job
	 * @param groupName
	 * @param jobName
	 */
	public void removeScheduleJob(String groupName,String jobName){
		scheduleJobMap.remove(getKey(groupName, jobName));
	}
}


;