Answer: use @DisallowConcurrentExecution
Example
Without this annotation
import java.time.LocalTime;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class HelloJob implements Job {
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
System.out.println(Thread.currentThread().getName() + ":Job started at " + LocalTime.now());
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName() + ":Job done at " + LocalTime.now());
}
}
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
public class DisallowConcurrentExecutionExample {
public static void main(String[] args) throws Exception {
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
scheduler.start();
JobDetail job = JobBuilder.newJob(HelloJob.class).withIdentity("helloJob", "anyGroup").build();
Trigger trigger = TriggerBuilder.newTrigger().withIdentity("helloTrigger", "anyGroup")
.withSchedule(simpleSchedule()
.withIntervalInSeconds(5) //re-fire every five minutes
.withRepeatCount(2)) //so with the first invocation together there will be 3 times
.startNow().build();
scheduler.scheduleJob(job, trigger);
}
}
And the output will be
LearnQuartz_Worker-1:Job started at 18:31:28.296 LearnQuartz_Worker-2:Job started at 18:31:33.275 #the first run hasn't been finished yet! LearnQuartz_Worker-3:Job started at 18:31:38.275 LearnQuartz_Worker-1:Job done at 18:31:38.353 LearnQuartz_Worker-2:Job done at 18:31:43.275 LearnQuartz_Worker-3:Job done at 18:31:48.275
Now if you put @DisallowConcurrentExecution to HelloJob class, the output will be like,
LearnQuartz_Worker-1:Job started at 18:34:44.665 LearnQuartz_Worker-1:Job done at 18:34:54.723 LearnQuartz_Worker-2:Job started at 18:34:54.726 #On hold until the first run has finished LearnQuartz_Worker-2:Job done at 18:35:04.726 LearnQuartz_Worker-3:Job started at 18:35:04.727 LearnQuartz_Worker-3:Job done at 18:35:14.727
That’s what we want.