2011-12-12 97 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。)

相關問題