试用了一下Quartz,功能很强大,可惜以前已经有这方面的设计了,要替换的话,工作量太大了。
对于以前经常碰到的一个问题:超时(TimeOut)的处理机制,好像Quartz里面没有相关的处理对策,于是试着写了一个:
import org.apache.log4j.Logger;
import org.quartz.InterruptableJob;
import org.quartz.JobExecutionContext;
import org.quartz.UnableToInterruptJobException;
/**
*
* @author zhoucan
*/
public class TimeOutThread extends Thread{
private static Logger log = Logger.getLogger(TimeOutThread.class);
private static long DEFAULT_TIMEOUT = 100l; //缺省的超时时间是100S;
private JobExecutionContext context;
private long timeout = -1l; //超时的秒数;
private TimeOutThread(){
super();
}
public TimeOutThread(JobExecutionContext context){
this();
this.context = context;
if( context != null ){
long _temp = context.getJobDetail().getJobDataMap().getLong("TimeOut");
this.timeout = _temp > 0l ? _temp : DEFAULT_TIMEOUT;
}
}
public void run(){
if( timeout == -1 )
return;
try{
sleep(timeout * 1000l);
}catch(InterruptedException ire){
log.error(ire);
}
try {
((InterruptableJob) context.getJobInstance())
.interrupt();
} catch (UnableToInterruptJobException e) {
throw new RuntimeException("exception", e);
}
}
}
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
/**
*
* @author zhoucan
*/
public class DefaultListener implements JobListener{
private final static Logger log = Logger.getLogger(DefaultListener.class);
TimeOutThread _timeout;
public String getName() {
return "DefaultListener";
}
public void jobExecutionVetoed(JobExecutionContext context) {
// TODO Auto-generated method stub
}
public void jobToBeExecuted(JobExecutionContext context) {
_timeout = new TimeOutThread(context);
_timeout.start();
}
public void jobWasExecuted(JobExecutionContext context,
JobExecutionException jobException) {
_timeout.interrupt();
}
}
主要原理是利用JobListener机制,Job开始执行时,启动一个值守的Thread,先休眠规定的TimeOut时间,等休眠完后,假如还未执行完,就将这个Job给interrupt调。
没有正式使用过,只是做了一些小范围的测试。欢迎大家斧正!