2011-12-12 76 views
6

我在下面的代码中运行两个任务。首先间隔10秒,另一间隔3秒。但最终在某个时候他们会同时执行。是否有任何机制,以避免这种情况如何避免两个作业同时在Quartz中运行?

JobDetail jDetail = new JobDetail("Job1", "group1", MyJob.class); 
    CronTrigger crTrigger = new CronTrigger("cronTrigger", "group1", "0/10 * * * * ?"); 
    sche.scheduleJob(jDetail, crTrigger); 

    jDetail = new JobDetail("Job2","group2",MyJob2.class); 
    crTrigger = new CronTrigger("cronTrigger2","group2","0/3 * * * * ?"); 
    sche.scheduleJob(jDetail, crTrigger); 
+0

您是否试图确保作业不会在同一个JVM或多个JVM中运行两次?另外,每项任务需要多长时间?他们是几秒钟,几秒钟,几分钟? – Bill

回答

2

您可以创建一个辅助对象,以使这两项工作同步:

//In the base class 
public static Object lock = new Object(); 

//In the first class 
public void execute() { 
    synchronized(lock) { 
     //do stuff 
    } 
} 

//In the second class 
public void execute() { 
    synchronized(lock) { 
     //do stuff 
    } 
} 

阅读在更多关于同步: http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html

+1

但OP说他跑两个不同的班,这不会解决他的情况 –

+0

@AngeloNeuschitzer你是绝对正确的,没有赶上那里有不同班级的工作。 –

3

不完全回答你的问题,但这是你如何查询以线程安全方式运行的东西:

//sched is your org.quartz.Scheduler 
     synchronized (sched) { 
      JobDetail existingJobDetail = sched.getJobDetail(jobName, jobGroup); 
      if (existingJobDetail != null) { 
       List<JobExecutionContext> currentlyExecutingJobs = (List<JobExecutionContext>) sched.getCurrentlyExecutingJobs(); 
       for (JobExecutionContext jec : currentlyExecutingJobs) { 

        if (existingJobDetail.equals(jec.getJobDetail())) { 
         // This job is currently executing 
        } 
       } 
      } 
+0

使用Scheduler作为监视对象的好主意! –

0

你试过:

org.quartz.jobStore.isClustered: true 

或者,你让你的工作成为一个有状态的工作(并设置isClustered为true),以及shoujld解决您的问题。 (糟糕,StatefulJob已弃用;请使用DisallowConcurrentExecution。)

相关问题