Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid two jobs running at the same time in Quartz?

I have tritten below code in which I am running two jobs. First with the interval of 10 seconds and the other with the interval of 3 seconds. But ultimately at some point they will execute at the same time. Is there any mechanism to avoid this situation

    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);
like image 933
user968880 Avatar asked Dec 12 '11 11:12

user968880


4 Answers

Not completely answering your question but this is how you can query for something running in a thread-safe manner:

//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
                    }
                }
            }
like image 95
dimitrisli Avatar answered Nov 15 '22 20:11

dimitrisli


Configure the Quartz threadpool to have only one thread.

org.quartz.threadPool.threadCount=1
like image 44
Kieren Dixon Avatar answered Nov 15 '22 21:11

Kieren Dixon


You could create a helper object to make the two jobs synchronized:

//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
    }
}

Read more about synchronization at: http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html

like image 30
Thomas Johan Eggum Avatar answered Nov 15 '22 22:11

Thomas Johan Eggum


Have you tried:

org.quartz.jobStore.isClustered: true

Alternatively, you make your job into a Stateful job (and set isClustered to true), and that shoujld solve your problem. (Oops, StatefulJob is deprecated; use DisallowConcurrentExecution.)

like image 28
jedison Avatar answered Nov 15 '22 20:11

jedison