How to interrupt or stop currently running quartz job?
You need to write a your job as an implementation of InterruptableJob.
To interrupt this job, you need handle to Scheduler , and call interrupt(jobKey<<job name & job group>>)
Please have a look @ javadoc for above classes, also quartz distribution contains an example for this (example7).
In Quartz 2.1 with Spring you can:
@Autowired
private Scheduler schedulerFactoryBean; //injected by spring
...
...
List<JobExecutionContext> currentlyExecuting = schedulerFactoryBean.getCurrentlyExecutingJobs();
//verifying if job is running
for (JobExecutionContext jobExecutionContext : currentlyExecuting) {
if(jobExecutionContext.getJobDetail().getKey().getName().equals("JobKeyNameToInterrupt")){
result = schedulerFactoryBean.interrupt(jobExecutionContext.getJobDetail().getKey());
}
}
The best solution in my opinion is the one described in this thread: http://forums.terracotta.org/forums/posts/list/7700.page
I've just introduced a "sleep" after set stop flag to true to allow the job to finish cleanly.
@Override
public void interrupt() throws UnableToInterruptJobException {
stopFlag.set(true);
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
//logger.error("interrupt()", e);
}
Thread thread = runningThread.getAndSet(null);
if (thread != null)
thread.interrupt();
}