Quartz did a good job on implementing this concept. It was very easy to add this feature by implementing a base class that abstract the details of interrupt and have every job extend this class. If you can rely on thread.interrupt() then its the best way to interrupt a job that is blocked on some I/O or native call. However if its a normal job then a simple boolean flag would do the work.
You would need to use scheduler.interrupt(jobName, groupName); to interrupt a running Quartz job.
You would need to use scheduler.interrupt(jobName, groupName); to interrupt a running Quartz job.
public abstract class BaseInterruptableJob implements InterruptableJob {
private static final AppLogger logger = AppLogger.getLogger(BaseInterruptableJob.class);
private Thread thread;
@Override
public void interrupt() throws UnableToInterruptJobException {
logger.info("Interrupting job " + getClass().getName());
if (thread != null) {
thread.interrupt();
}
}
@Override
final public void execute(JobExecutionContext context) throws JobExecutionException {
try {
thread = Thread.currentThread();
interruptableExecute(context);
} finally {
thread = null;
}
}
protected abstract void interruptableExecute(JobExecutionContext context) throws JobExecutionException;
}
package net.nighttale.scheduling;
ReplyDeleteimport org.quartz.*;
public class QuartzReport implements Job {
public void execute(JobExecutionContext cntxt)
throws JobExecutionException {
System.out.println(
"Generating report - " +
cntxt.getJobDetail().getJobDataMap().get("type")
);
//TODO Generate report
}
public static void main(String[] args) {
try {
SchedulerFactory schedFact
new org.quartz.impl.StdSchedulerFactory();
Scheduler sched schedFact.getScheduler();
sched.start();
JobDetail jobDetail
new JobDetail(
"Income Report",
"Report Generation",
QuartzReport.class
);
jobDetail.getJobDataMap().put(
"type",
"FULL"
);
CronTrigger trigger new CronTrigger(
"Income Report",
"Report Generation"
);
trigger.setCronExpression(
"0 0 12 ? * SUN"
);
sched.scheduleJob(jobDetail, trigger);
} catch (Exception e) {
e.printStackTrace();
}
}
}
How stop Job here any suggestion please?
well from the program it seems you are running a main program and not a web application so the only way you can stop this is to start another thread in application that is listening a port for some commands and when you receive the stop command you can stop your scheduler. Or you can embed a mini http server in the app and then use the request parameter to trigger the stop.
ReplyDelete