首先执行的class 需要继承 QuartzJobBean 这个类,我这个是一个抽象类,先继承了QuartzJobBean 然后其他需要执行的class再继承他,我只是加了一个执行前执行后需要执行的方法。
package xxxxx.batchjob.job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;
public abstract class TestJobTemlate extends QuartzJobBean {
private final Logger log = LoggerFactory.getLogger(TestJobTemlate .class);
protected abstract void preExecute();
protected abstract void postExecute();
protected abstract void executeTestJob(JobExecutionContext context) throws JobExecutionException;
@Override
public final void executeInternal(JobExecutionContext context) throws JobExecutionException{
preExecuteInternal();
executeTestJob(context);
postExecuteInternal();
}
public final void preExecuteInternal() {
log.info("Execute job :"+this.getClass().getName() + " Start >>>>>>>>>>>>>>");
preExecute();
}
public final void postExecuteInternal() {
postExecute();
log.info("Execute job :"+this.getClass().getName() + " End >>>>>>>>>>>>>>");
}
}
需要执行的java class 继承我们自定义好的类,再重写定义好的方法,在 executeTestJob 里面写需要执行的代码就可以了,preExecute 写执行代码之前需要执行的操作,postExecute 写执行代码之后需要执行的操作。加不加DisallowConcurrentExecution的区别就是,cron时间到了之后是否等待上一次job执行完成,加了就不会等待,cron时间一到就执行,不加的话会等待。
package xxxx.batchjob.job;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
@DisallowConcurrentExecution
public class TestJob extends TestJobTemlate {
@Override
protected void preExecute() {
// TODO Auto-generated method stub
}
@Override
protected void postExecute() {
// TODO Auto-generated method stub
}
@Override
protected void executeTestJob(JobExecutionContext context) {
// need axecute function
}
}
}
最后在jobBuilder build job的时候把class放进去就可以了。 当然这个class name可以从front-end传过来的,我这里只是hardcode而已
Class cls=(Class<? extends Job>) Class.forName("xxxx.batchjob.Testjob")
JobBuilder.newJob(cls).withIdentity(jobKey).withDescription(description).setJobData(map).storeDurably().build();