spring quartz 动态任务

/**
	 * 增加定时任务
	 */
	@Override
	public void addJob(TaskTrggerInfo trggerInfo) throws Exception {
		Scheduler scheduler=StdSchedulerFactory.getDefaultScheduler();

		JobDataMap jobDataMap = new JobDataMap();
		// 需要保存spring的bean类 才能反射出 调用方法
		jobDataMap.put("targetObject",
				springUtil.getBean(trggerInfo.getTargetObject()));
		// 调用方法
		jobDataMap.put("targetMethod", trggerInfo.getTargetMethod());
		jobDataMap.put("shouldRecover", "true");
		
		JobDetail jobDetail=new JobDetail();
		jobDetail.setGroup(GROUP);
		jobDetail.setName(trggerInfo.getJobName());
		jobDetail.setJobClass(MethodInvokingJobDetailFactoryBean.MethodInvokingJob.class);
		jobDetail.setJobDataMap(jobDataMap);
		
		//设置触发器
		CronTrigger cronTrigger = new CronTrigger(trggerInfo.getJobName()+"_Trigger",GROUP);
		// 设置任务触发时间
		CronExpression cexp = new CronExpression(trggerInfo.getCronExpression());
		// 设置触发器
		cronTrigger.setCronExpression(cexp);
		
		scheduler.scheduleJob(jobDetail, cronTrigger);
//		scheduler.addJob(jobDetail, true);
	}

	/**
	 * 删除定时任务
	 */
	@Override
	public void deleteJob(String jobName, String jobGroup) throws Exception {
		Scheduler scheduler=StdSchedulerFactory.getDefaultScheduler();
		scheduler.deleteJob(jobName, jobGroup);
	}

	/**
	 * 暂停订时任务
	 */
	@Override
	public void updatePauseTrigger(String triggerName, String group)
			throws Exception {
		Scheduler scheduler=StdSchedulerFactory.getDefaultScheduler();
		scheduler.pauseTrigger(triggerName, group);
	}

	/**
	 * 重启任务
	 */
	@Override
	public void updateResumeTrigger(String triggerName, String group)
			throws Exception {
		Scheduler scheduler=StdSchedulerFactory.getDefaultScheduler();
		//先停止
		scheduler.pauseTrigger(triggerName, group);
		//在重启
		scheduler.resumeTrigger(triggerName, group);
	}
/**
	 * 重置cron类型的任务表达式
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void rescheduleJob(TaskTrggerInfo taskTrggerInfo) throws Exception{
		Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
		CronTrigger cronTrigger = new CronTrigger();
		//设置触发器名称
		cronTrigger.setName(taskTrggerInfo.getTriggerName());
		//设置分组信息
		cronTrigger.setGroup(taskTrggerInfo.getJobGroup());
		//设置任务名称
		cronTrigger.setJobName(taskTrggerInfo.getJobName());
		//设置任务分组
		cronTrigger.setJobGroup(taskTrggerInfo.getJobGroup());
		// 设置任务触发表达式
		CronExpression cexp = new CronExpression(taskTrggerInfo.getCronExpression());
//		 //设置触发器
		cronTrigger.setCronExpression(cexp);
		scheduler.rescheduleJob(taskTrggerInfo.getTriggerName(), taskTrggerInfo.getJobGroup(), cronTrigger);
		//更新任务详情
		updateTaskInfo(taskTrggerInfo);
	}

你可能感兴趣的:(spring quartz 动态任务)