我有一个Quartz作业,设置为每周定时运行。但是,我想阻止同时执行此作业。我将@DisallowConcurrentExecution注释添加到代表此作业的类中,但这似乎没有任何效果。
以下是我创建作业和触发器存储到JDBC存储中的方法。触发器设置为每5秒运行一次。
JobKey jobKey = new JobKey("sample_job", "default_group");
String triggerIdentity = jobKey.getName() + "_trigger";
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
if (!scheduler.checkExists(jobKey)) {
JobDetail jobDetail = JobBuilder.newJob(SampleJob.class).withIdentity(jobKey).build();
Trigger trigger = newTrigger()
.withIdentity(triggerIdentity, jobKey.getGroup())
.startAt(new Date())
.withSchedule(simpleSchedule()
.withIntervalInSeconds(5)
.repeatForever())
.build();
scheduler.scheduleJob(jobDetail, trigger);
}
scheduler.start();
以下是我创建的示例作业类。它基本上会启动一个在10秒内完成的计时器并打印一条消息。
@DisallowConcurrentExecution
public class SampleJob implements Job {
public SampleJob() {
}
@Override
public void execute(JobExecutionContext jobExcutionContext) {
final Date now = new Date();
System.out.println("Starting sample job: " + now);
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Done: " + now);
this.cancel();
}
}, 10000L);
}
}
当我运行它时,我看到以下输出,这对我来说表明即使先前的执行尚未完成,作业也会每5秒触发一次。我是否误解了@DisallowConcurrentExecution的含义,还是我的测试不正确?
Starting sample job: Sat Apr 04 22:45:06 EDT 2015
Starting sample job: Sat Apr 04 22:45:11 EDT 2015
Done: Sat Apr 04 22:45:01 EDT 2015
Starting sample job: Sat Apr 04 22:45:16 EDT 2015
Done: Sat Apr 04 22:45:06 EDT 2015
Starting sample job: Sat Apr 04 22:45:21 EDT 2015
Done: Sat Apr 04 22:45:11 EDT 2015
Done: Sat Apr 04 22:45:16 EDT 2015
Starting sample job: Sat Apr 04 22:45:26 EDT 2015
Starting sample job: Sat Apr 04 22:45:31 EDT 2015
Done: Sat Apr 04 22:45:21 EDT 2015
答案 0 :(得分:0)
事实证明我正在过度思考这个问题。一个计时器似乎是一个单独的线程。因此,就工作而言,它是在计时器完成之前完成的。一个简单的Thread.sleep(10000)代替了Timer就可以了。