Scheduler 动态定时任务



/**
 * 定时任务管理类
 * 
 * @author
 *
 */
public class QuartzManager {

	static Logger logger = Logger.getLogger("QuartzManager");
	// 创建一个SchedulerFactory工厂实例
	private static SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
	// 任务组
	private static String JOB_GROUP_NAME = "JOBGROUP_NAME";
	// 触发器组
	private static String TRIGGER_GROUP_NAME = "TRIGGERGROUP_NAME";

	/**
	 * 添加定时周期任务。时间:秒
	 * 
	 * @param JOBID
	 * @param jobClass
	 * @param seconds
	 * @param repeatCount
	 * @param delayed
	 * @param parameter
	 */
	public static void addJob(String JOBID, Class jobClass, int seconds, int repeatCount, int delayed,Map parameter) {
		try {
			//开始时间
			Date startTime = new Date(System.currentTimeMillis() + delayed * 1000);
			JobKey jobkey = new JobKey(JOBID, TRIGGER_GROUP_NAME);
			Scheduler sched = gSchedulerFactory.getScheduler();
			boolean exists = sched.checkExists(jobkey);
			if(exists){
				logger.info(JOBID+" 任务已存在");
				return;
			}
			// 任务名,任务组,任务执行类
			JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(JOBID, TRIGGER_GROUP_NAME).requestRecovery().build();
			// 传参数
			jobDetail.getJobDataMap().put("parameterList", parameter);
			// 触发器
			SimpleScheduleBuilder builder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(seconds).withRepeatCount(repeatCount);
			Trigger trigger = TriggerBuilder.newTrigger().withIdentity(JOBID, TRIGGER_GROUP_NAME).startAt(startTime).withSchedule(builder).build();
			sched.scheduleJob(jobDetail, trigger);
			if (!sched.isShutdown()) {
				// 延迟启动
				sched.start();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 添加定时一次性任务
	 * 
	 * @param JOBID
	 * @param jobClass
	 * @param time
	 * @param parameter
	 */
	public static void addOnetimeJob(String JOBID, Class jobClass, String time,Map parameter) {
		try {
			//开始时间
			Date startTime = DateUtil.fomatDateSs(time);
			JobKey jobkey = new JobKey(JOBID, TRIGGER_GROUP_NAME);
			Scheduler sched = gSchedulerFactory.getScheduler();
			boolean exists = sched.checkExists(jobkey);
			if(exists){
				logger.info(JOBID+" 任务已存在1");
				return;
			}
			// 任务名,任务组,任务执行类
			JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(JOBID, TRIGGER_GROUP_NAME).requestRecovery().build();
			// 传参数
			jobDetail.getJobDataMap().put("parameterList", parameter);
			// 触发器
			SimpleScheduleBuilder builder = SimpleScheduleBuilder.simpleSchedule();
			Trigger trigger = TriggerBuilder.newTrigger().withIdentity(JOBID, TRIGGER_GROUP_NAME).startAt(startTime).withSchedule(builder).build();
			sched.scheduleJob(jobDetail, trigger);
			if (!sched.isShutdown()) {
				// 延迟启动
				sched.start();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 移除一个任务(使用默认的任务组名,触发器名,触发器组名)
	 * 
	 * @param jobName
	 *            任务名称
	 */
	public static void removeJob(String jobName) {
		try {
			Scheduler sched = gSchedulerFactory.getScheduler();
			// 通过触发器名和组名获取TriggerKey
			TriggerKey triggerKey = TriggerKey.triggerKey(jobName, TRIGGER_GROUP_NAME);
			// 通过任务名和组名获取JobKey
			JobKey jobKey = JobKey.jobKey(jobName, JOB_GROUP_NAME);
			sched.pauseJob(jobKey);
			// 停止触发器
			sched.pauseTrigger(triggerKey);
			// 移除触发器
			sched.unscheduleJob(triggerKey);
			// 删除任务
			sched.deleteJob(jobKey);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static void completeStopJob(String jobName) {
		try {
			Scheduler sched = gSchedulerFactory.getScheduler();
			TriggerKey triggerKey = TriggerKey.triggerKey(jobName, TRIGGER_GROUP_NAME);
			TriggerState state = sched.getTriggerState(triggerKey);
			switch (state) {
			case COMPLETE:
				logger.info(jobName+"任务完成.");
				break;
			case PAUSED:
				logger.info(jobName+"任务暂停.");
				break;
			case ERROR:
				logger.info(jobName+"任务错误.");
				break;
			case NORMAL:
				logger.info(jobName+"任务正常.");
				break;
			case BLOCKED:
				logger.info(jobName+"任务阻塞.");
				break;
			case NONE:
				logger.info(jobName+"任务不存在.");
				break;
			default:
				break;
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 启动所有定时任务
	 */
	public static void startJobs() {
		try {
			Scheduler sched = gSchedulerFactory.getScheduler();
			sched.start();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 关闭所有定时任务
	 */
	public static void shutdownJobs() {
		try {
			Scheduler sched = gSchedulerFactory.getScheduler();
			if (!sched.isShutdown()) {
				sched.shutdown();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}


	public static void main(String[] args) {
		Map parameter = new HashMap();
		parameter.put("ID", JOBID);
		parameter.put("EXEITEM", EXEITEM);
		QuartzManager.addJob(JOBID,PushQuartzJob.class,2*60,1,1*60,parameter); 

		QuartzManager.addOnetimeJob(JOBID,PushQuartzJob.class,"2025-06-07 04:38:46",parameter); 
				
	}
}



/** quartz 定时任务调度
 */
public class PushQuartzJob extends BaseController implements Job{

	Logger logger = Logger.getLogger(this.getClass());
	
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		// TODO Auto-generated method stub
		JobDataMap dataMap = context.getJobDetail().getJobDataMap();	
		//获取参数
		Map parameter = (Map)dataMap.get("parameterList");
		String ID = parameter.get("ID").toString();
		final int exeItem = Integer.parseInt(parameter.get("EXEITEM").toString());

		//更新状态
		QuartzManager.completeStopJob(ID2);

		//异常时关闭任务
		context.getScheduler().shutdown();	
	}
	

}

CODE

你可能感兴趣的:(java,java,开发语言)