Quartz動態添加定時任務

1.添加Quartz的依賴java

<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz</artifactId>
			<version>2.2.1</version>
		</dependency>
		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz-jobs</artifactId>
			<version>2.2.1</version>
		</dependency>

2.定時任務的工具類 spring

import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.EverythingMatcher;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


/**
 * Quartz 管理器(暫不支持集羣處理)
 * 
 * @author listen
 */
@Component
public class QuartzManagerUtil {
	private static Logger logger = LoggerFactory.getLogger(QuartzManagerUtil.class);
	private static SchedulerFactory schedulerFactory;
	private static Scheduler scheduler;
	
	QuartzManagerUtil(){
		try {
			schedulerFactory = new StdSchedulerFactory();
			scheduler = schedulerFactory.getScheduler();
			scheduler.getListenerManager().addJobListener(new JobRunLogInterceptor(), EverythingMatcher.allJobs());
			scheduler.start();
		}catch (Exception e) {
			logger.error("Quartz 管理器初始化失敗");
		}
		
	}

	/**
	 * 添加Job
	 */
	public static void addJob(String jobName, String cronTime, Class jobClass) {
		try {
			JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobName, jobName + "_Group").build();
			CronTrigger cronTrigger = new CronTriggerImpl(jobName + "_CronTrigger", jobName + "_TriggerGroup", cronTime);
			scheduler.scheduleJob(jobDetail, cronTrigger);
		} catch (Exception ex) {
			logger.error("添加定時任務[" + jobName + "]失敗:" + ex.getMessage());
		}
	}

	/**
	 * 刪除Job
	 */
	public static void deleteJob(String jobName) {
		try {
			JobKey jk = new JobKey(jobName, jobName + "_Group");
			scheduler.deleteJob(jk);
		} catch (Exception ex) {
			logger.error("刪除定時任務[" + jobName + "]失敗:" + ex.getMessage());
		}
	}

	/**
	 * 暫停全部Job
	 */
	public static void PauseAll() {
		try {
			scheduler.pauseAll();
		} catch (Exception ex) {
			logger.error("暫停全部Job失敗:" + ex.getMessage());
		}
	}

	/**
	 * 恢復全部Job
	 */
	public static void ResumeAll() {
		try {
			scheduler.resumeAll();
		} catch (Exception ex) {
			logger.error("恢復全部Job失敗:" + ex.getMessage());
		}
	}

	/**
	 * 卸載定時器
	 */
	public static void shutdown(Boolean waitForJobsToComplete) {
		try {
			scheduler.shutdown(waitForJobsToComplete);
		} catch (Exception ex) {
			logger.error("卸載定時器失敗:" + ex.getMessage());
		}
	}
}

3.Quartz監聽器,跟蹤在不一樣階段任務的執行狀態dom

import java.io.PrintWriter;
import java.io.StringWriter;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import cn.lecons.gcb.foundation.domain.RunLog;
import cn.lecons.gcb.foundation.service.RunLogService;
import cn.lecons.gcb.foundation.service.RunLogServiceImpl;
import cn.lecons.gcb.foundation.util.BeanFactoryUtil;
import cn.lecons.gcb.framework.exception.BusinessException;

/**
 * @author listen
 */
public class JobRunLogInterceptor implements JobListener {
	private static Logger logger = LoggerFactory.getLogger(JobRunLogInterceptor.class);
	/**
	 * 用於獲取該JobListener的名稱
	 */
	@Override
	public String getName() {
		String name = getClass().getSimpleName();
		return name;
	}

	/**
	 * Scheduler在JobDetail將要被執行時調用這個方法
	 */
	@Override
	public void jobToBeExecuted(JobExecutionContext context) {
		String jobName = context.getJobDetail().getKey().getName();
		logger.error("定時任務: "+jobName+" 開始執行!");
	}

	/**
	 * Scheduler在JobDetail即將被執行,但又被TriggerListerner否決時會調用該方法
	 */
	@Override
	public void jobExecutionVetoed(JobExecutionContext context) {
	}

	/**
	 * Scheduler在JobDetail被執行以後調用這個方法
	 */
	@Override
	public void jobWasExecuted(JobExecutionContext context, JobExecutionException exception) {
		String jobName = context.getJobDetail().getKey().getName();
		long runtime = context.getJobRunTime();
		RunLogService runLogService = BeanFactoryUtil.getBean("runLogService");
		if (exception != null) {
			if (exception.getCause() != null && exception.getCause().getCause() instanceof BusinessException) {
				BusinessException businessException = (BusinessException) exception.getCause().getCause();
				String msg = StringUtils.isEmpty(businessException.getMessage())
						? (businessException.getErrorCode() == null ? ""
								: businessException.getErrorCode().getMessage())
						: businessException.getMessage();
				RunLog runLog = new RunLog();
				runLog.setModule("業務異常");
				runLog.setAction(jobName + "-定時任務");
				runLog.setRunTime(runtime);
				runLog.setMessage(msg);
				runLog.setExceptionDetail(msg);
				runLogService.createBusinessLog(runLog);
			} else {
				RunLog exRunInfo = new RunLog();
				exRunInfo.setModule("系統異常");
				exRunInfo.setAction(jobName + "-定時任務");
				exRunInfo.setRunTime(runtime);
				StringWriter stringWriter = new StringWriter();
				PrintWriter printWriter = new PrintWriter(stringWriter);
				exception.printStackTrace(printWriter);
				String exceptionString = stringWriter.getBuffer().toString();
				exRunInfo.setExceptionDetail(exceptionString);
				runLogService.createExceptionLog(exRunInfo);
			}
		} else {
			logger.error("定時任務: " + jobName + " 執行完畢,共耗時(mm):" + runtime);
		}
	}
}

4.添加任務 TestJob爲要執行的具體任務ide

import org.springframework.stereotype.Service;

import com.roncoo.education.task.TestJob;

import com.roncoo.education.util.quartz.QuartzManagerUtil;

/**

 */
@Service
public class JobServiceImpl implements RunLogService {

	@Override
	public void testJob(Integer id) {
			String jobName = "jobName";
			String cronTime = "0/5 * * * * ? ";
			
			//TestJob須要執行的任務
			Class jobClass = TestJob.class;
			for(int i = 0 ;i<5;i++) {
				QuartzManagerUtil.addJob(jobName+i , cronTime,  jobClass);
			}
	}	
 
}

5.TestJob工具

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.roncoo.education.util.quartz.QuartzManagerUtil;

public class TestJob implements Job{


	@Override
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		
		//arg0.getJobDetail().getKey().getName();得到任務的名字
		String jobName = arg0.getJobDetail().getKey().getName();
		System.out.println(jobName+"+執行了");
		
		
		//任務執行完刪除
		QuartzManagerUtil.deleteJob(jobName);
		
	}
}
相關文章
相關標籤/搜索