Checking if a Quartz job is already running

Posted on 04-01-2013 11:33 by graham
When using Quartz jobs in Java, it often happens that we only want to run a job if its previous iteration has finished executing. Below is a way to check if a previous instance of the job has finished executing, and runs only if the previous iteration has terminated.
public class SomeJob implements Job
{
@Override
public void execute(JobExecutionContext ctx) throws JobExecutionException
{
// check if a previous iteration of this job is still running
if (isJobRunning(ctx))
{
// previous iteration still running, skip
return;
}

// do the actual work
...
}

@SuppressWarnings("unchecked")
private boolean isJobRunning(JobExecutionContext ctx) throws SchedulerException
{
List<JobExecutionContext> jobs = ctx.getScheduler().getCurrentlyExecutingJobs();

for (JobExecutionContext job : jobs)
{
// check if the current job is already running (make sure to check that fire times are different so that a different
// instance of the same job is checked)
if (job.getJobDetail().getJobClass().getName().equals(this.getClass().getName()) && !job.getFireTime().equals(ctx.getFireTime()))
{
return true;
}
}

return false;
}
}
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems