quartz 动态增加定时任务

原创
2016/09/29 14:40
阅读数 662

spring bean类

<!-- ======================== 调度工厂 ======================== -->
	<bean id="SpringJobSchedulerFactoryBean"
		class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="configLocation" value="classpath:quartz.properties" />
		<property name="dataSource" ref="dataSource" />
<!-- 		<property name="triggers"> -->
<!-- 			<list> -->
<!-- 				<ref bean="settleAccountJobTriggerBean" /> -->
<!-- 				<ref bean="updateCompetitionStatusQuartzTriggerBean" /> -->
<!-- 			</list> -->
<!-- 		</property> -->
	</bean>

quartz.properties 属性文件



##wanghao
org.quartz.scheduler.instanceName = gamemanagerQuartzScheduler   
org.quartz.scheduler.instanceId = AUTO    
#============================================================================   
# Configure ThreadPool     
#============================================================================  
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool  
org.quartz.threadPool.threadCount = 5  
org.quartz.threadPool.threadPriority = 5


org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true


org.quartz.jobStore.class =org.quartz.impl.jdbcjobstore.JobStoreTX  
#org.quartz.jobStore.driverDelegateClass =org.quartz.impl.jdbcjobstore.StdJDBCDelegate 
org.quartz.jobStore.driverDelegateClass =org.quartz.impl.jdbcjobstore.oracle.OracleDelegate 
org.quartz.jobStore.misfireThreshold =60000
org.quartz.jobStore.tablePrefix=QRTZ_    
org.quartz.jobStore.maxMisfiresToHandleAtATime=10   
org.quartz.jobStore.isClustered =true    
org.quartz.jobStore.clusterCheckinInterval =15000

测试类 

public class TestScheduler extends BaseTest {
	private static Scheduler scheduler;

	@Test
	public void testJob() throws SchedulerException {
		scheduler = SpringApplicationContext.getBean("SpringJobSchedulerFactoryBean");
		ScheduleJob job = new ScheduleJob();
		job.setCronExpression("59 * * * * ?");
//////		job.setDesc("xx");
//////		job.setJobGroup("scheduleJob");
//		job.setJobName("broadCast");
//////		job.setJobStatus("x");
////		
//		startJob(job);
		
		deleteJob();
		
//		getJobAll();
	}

	public static void startJob(ScheduleJob job) throws SchedulerException{
		TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName() , job.getJobGroup());
		CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
		            // 不存在,创建一个
		            if (null == trigger) {
		                JobDetail jobDetail = JobBuilder.newJob(QuartzJobFactory.class).withIdentity(job.getJobName(), job.getJobGroup()).build();
		                jobDetail.getJobDataMap().put("scheduleJob", job);
		                // 表达式调度构建器
		                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
		                // 按新的cronExpression表达式构建一个新的trigger
		                trigger = TriggerBuilder.newTrigger().withIdentity(job.getJobName(), job.getJobGroup()).withSchedule(scheduleBuilder).build();
		                scheduler.scheduleJob(jobDetail, trigger);
		            } else {
		                // Trigger已存在,那么更新相应的定时设置
		                // 表达式调度构建器
		                CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
		                // 按新的cronExpression表达式重新构建trigger
		                trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
		                // 按新的trigger重新设置job执行
		                scheduler.rescheduleJob(triggerKey, trigger);
		            }

	}
	/**
	 * 暂停Job
	 * 
	 * @param scheduleJob
	 * @throws SchedulerException
	 */
	public static void pauseJob(ScheduleJob scheduleJob) throws SchedulerException {
		JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
		scheduler.pauseJob(jobKey);
	}

	/**
	 * 恢复Job
	 * 
	 * @param scheduleJob
	 * @throws SchedulerException
	 */
	public static void resumeJob(ScheduleJob scheduleJob) throws SchedulerException {
		JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
		scheduler.resumeJob(jobKey);
	}

	/**
	 * 立即运行任务一次
	 * 
	 * @param scheduleJob
	 * @throws SchedulerException
	 */
	public static void triggerJob(ScheduleJob scheduleJob) throws SchedulerException {
		JobKey jobKey = JobKey.jobKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
		scheduler.triggerJob(jobKey);
	}

	/**
	 * 更新任务表达式
	 * 
	 * @param scheduleJob
	 * @throws SchedulerException
	 */
	public static void rescheduleJob(ScheduleJob scheduleJob) throws SchedulerException {
		TriggerKey triggerKey = TriggerKey.triggerKey(scheduleJob.getJobName(), scheduleJob.getJobGroup());
		// 获取trigger,即在spring配置文件中定义的 bean id="myTrigger"
		CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
		// 表达式调度构建器
		CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression());
		// 按新的cronExpression表达式重新构建trigger
		trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
		// 按新的trigger重新设置job执行
		scheduler.rescheduleJob(triggerKey, trigger);
	}
	public void deleteJob() throws SchedulerException{
		try{
		boolean flag = scheduler.deleteJob(new JobKey("broadCast"));
		System.out.println(flag);
		} catch(Exception e){
			e.printStackTrace();
		}
	}

	public static void isRunJob() throws SchedulerException {
		List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
		List<ScheduleJob> jobList = new ArrayList<ScheduleJob>(executingJobs.size());
		for (JobExecutionContext executingJob : executingJobs) {
			ScheduleJob job = new ScheduleJob();
			JobDetail jobDetail = executingJob.getJobDetail();
			JobKey jobKey = jobDetail.getKey();
			Trigger trigger = executingJob.getTrigger();
			job.setJobName(jobKey.getName());
			job.setJobGroup(jobKey.getGroup());
			job.setDesc("触发器:" + trigger.getKey());
			Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
			job.setJobStatus(triggerState.name());
			if (trigger instanceof CronTrigger) {
				CronTrigger cronTrigger = (CronTrigger) trigger;
				String cronExpression = cronTrigger.getCronExpression();
				job.setCronExpression(cronExpression);
			}
			LOGGER.info("runing job is " + job.getJobName());
			jobList.add(job);
		}

	}
	
	/**
	 * 获取所有的Job
	 * 
	 * @throws SchedulerException
	 */
	public static void getJobAll() throws SchedulerException {
		// schedulerFactoryBean 由spring创建注入
		GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
		Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
		List<ScheduleJob> jobList = new ArrayList<ScheduleJob>();
		for (JobKey jobKey : jobKeys) {
			List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
			for (Trigger trigger : triggers) {
				ScheduleJob job = new ScheduleJob();
				job.setJobName(jobKey.getName());
				job.setJobGroup(jobKey.getGroup());
				job.setDesc("触发器:" + trigger.getKey());
				Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
				job.setJobStatus(triggerState.name());
				if (trigger instanceof CronTrigger) {
					CronTrigger cronTrigger = (CronTrigger) trigger;
					String cronExpression = cronTrigger.getCronExpression();
					job.setCronExpression(cronExpression);
				}
				LOGGER.info("all job is " + job.getJobName());
				jobList.add(job);
			}
		}
	}
}

 

展开阅读全文
打赏
0
2 收藏
分享
加载中
更多评论
打赏
0 评论
2 收藏
0
分享
返回顶部
顶部