当前位置:编程学习 > JAVA >>

求教:为什么Quartz同时执行两个任务会出问题

我是自己写单元测试类测的。附上部分关键代码

【初始化队列】
if (sched == null) {
  sched = org.quartz.impl.StdSchedulerFactory.getDefaultScheduler();
 }
 if (!sched.isStarted()) {
  sched.start();
 }
 


【注册任务】
// 创建任务
 org.quartz.JobDetail job = scheduler.toJobDetail();
 
 // 创建定时器
 org.quartz.Trigger trigger = scheduler.toTrigger();
 
 // 将任务放入定时队列
 try {
  Date date = sched.scheduleJob(job, trigger);
 

【生成JobDetail】
public JobDetail toJobDetail() {
  JobDataMap map = new JobDataMap();
 
  map.put(QJobDataMapKey.id.toString(), this.getId());
  map.put(QJobDataMapKey.beanName.toString(), this.getBeanName());
  map.put(QJobDataMapKey.className.toString(), this.getClassName());
  map.put(QJobDataMapKey.schedulerName.toString(), this.getName());
  map.put(QJobDataMapKey.bizData.toString(), JsonUtils.toJson(this.getExeParams()));
 
  return JobBuilder.newJob(QJob.class).withIdentity(this.getId()).usingJobData(map)
  .build();
 }
 

同一个任务的JobDetail的ID和Trigger的ID是一致的,由UUID生成。
【生成Trigger】
	// 首次执行时间
  long startDelay = new Date().getTime() + (this.startDelay * 1000);// 换算成毫秒
 
  SimpleScheduleBuilder builder = SimpleScheduleBuilder.repeatSecondlyForTotalCount(1);;
 
  return TriggerBuilder.newTrigger().withIdentity(id).startAt(new Date(startDelay))
  .withSchedule(builder).build();
 


定义了两个任务,其中任务NormalExecutor,1秒后执行,执行时打印信息。任务CompleteExecutor,10秒后执行,也是打印信息

【测试代码】
public static void main(String[] args) {
  SchedulerQueueSimpleTest test = new SchedulerQueueSimpleTest();
  test.addNormalExecutor();
  test.addCompleteExecutor();
 }
 


根据逻辑,先注册Normal,再注册Complete,应该1秒后先执行Normal,然后10秒后再执行Complete。
======NormalExecutorTest执行[Thu Nov 29 17:02:59 CST 2012]======
======CompleteExecutorTest执行[Thu Nov 29 17:03:08 CST 2012]======
好,事实确实如此,但是大家不要捉急,下面我们把测试代码小改一下。

public static void main(String[] args) {
   SchedulerQueueSimpleTest test = new SchedulerQueueSimpleTest();
   test.addCompleteExecutor();//这两行调换了位置
   test.addNormalExecutor();//就是它
  }
  


只是更换了两个任务的注册顺序而已。结果,竟然影响到了任务的执行。
请擦亮眼睛,看看后台打印

======NormalExecutorTest执行[Thu Nov 29 17:02:15 CST 2012]======
======CompleteExecutorTest执行[Thu Nov 29 17:02:15 CST 2012]======

看到没,竟然两个一起执行了!!!!

请教各位大大,谁能帮我解读这次灵异事件…… --------------------编程问答-------------------- 看不出来,也许出问题的不在你想的地方 --------------------编程问答-------------------- 终于有人回复了,还是谢谢有心人
补充:Java ,  Java相关
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,