Quartz 1.8.6 执行完当前任务才执行下一任务
公司项目比较老了,使用的是Quartz 1.8.6
这个定时任务默认是并发的,到点就执行
场景是定时任务调用供应商接口,重复下发,并发时出问题
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>1.8.6</version>
</dependency>
public class QuartzTest {
private static final SchedulerFactory gSchedulerFactory = new StdSchedulerFactory();
public static void main(String[] args) throws Exception {
Class cls = Class.forName("com.example.MyJob");
Scheduler sched = gSchedulerFactory.getScheduler();
JobDetail jobDetail = new JobDetail("模拟操作", "DEMO_JOBGROUP_NAME", cls);
CronTrigger trigger = new CronTrigger("模拟操作", "DEMO_TRIGGERGROUP_NAME");
trigger.setCronExpression("0/3 * * * * ?");
sched.scheduleJob(jobDetail, trigger);
if (!sched.isShutdown()) {
sched.start();
}
}
}
public class MyJob implements Job {
private static Integer count = 0;
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
try {
//获取一个1-15的随机整数
System.out.println("线程"+Thread.currentThread().getId()+"任务开始执行");
int i = (int) (Math.random() * 15 + 1);
System.out.println("线程"+Thread.currentThread().getId()+"开始执行,任务执行时间"+i+"秒");
Thread.sleep(i*1000);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
count++;
// 执行具体任务
System.out.println("线程"+Thread.currentThread().getId()+" MyJob is Running ..." + "执行第:" + count + "次" + " Date:" + sdf.format(new Date()));
System.out.println("线程"+Thread.currentThread().getId()+"完成执行,执行任务执行时间"+i+"秒");
System.out.println("---------------------------------------------------------------------");
} catch (InterruptedException e) {
throw new JobExecutionException(e);
}
}
}
更改为实现StatefulJob接口
public class MyJob implements StatefulJob {
private static Integer count = 0;
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
try {
//获取一个1-15的随机整数
System.out.println("线程"+Thread.currentThread().getId()+"任务开始执行");
int i = (int) (Math.random() * 15 + 1);
System.out.println("线程"+Thread.currentThread().getId()+"开始执行,任务执行时间"+i+"秒");
Thread.sleep(i*1000);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
count++;
// 执行具体任务
System.out.println("线程"+Thread.currentThread().getId()+" MyJob is Running ..." + "执行第:" + count + "次" + " Date:" + sdf.format(new Date()));
System.out.println("线程"+Thread.currentThread().getId()+"完成执行,执行任务执行时间"+i+"秒");
System.out.println("---------------------------------------------------------------------");
} catch (InterruptedException e) {
throw new JobExecutionException(e);
}
}
}
实现了一次任务执行完成,才执行下一次