我正在使用quartz-scheduler 1.8.5。我创建了一个实现StatefulJob接口的Job,使用SimpleTrigger和StdSchedulerFactory进行调度。
似乎我必须更新Trigger的JobDataMap以及JobDetail的JobDataMap才能从Job内部更改JobDataMap。我试图理解为什么需要同时更新两者?我注意到JobDataMap被设置为dirty。也许我需要显式保存它或做些其他的操作?
我想我必须深入Quartz的源代码才能真正理解这里发生了什么,但我想先懒一点并询问一下。感谢您对JobDataMap内部工作原理的任何见解!
这是我的Job:
似乎我必须更新Trigger的JobDataMap以及JobDetail的JobDataMap才能从Job内部更改JobDataMap。我试图理解为什么需要同时更新两者?我注意到JobDataMap被设置为dirty。也许我需要显式保存它或做些其他的操作?
我想我必须深入Quartz的源代码才能真正理解这里发生了什么,但我想先懒一点并询问一下。感谢您对JobDataMap内部工作原理的任何见解!
这是我的Job:
public class HelloJob implements StatefulJob {
public HelloJob() {
}
public void execute(JobExecutionContext context)
throws JobExecutionException {
int count = context.getMergedJobDataMap().getInt("count");
int count2 = context.getJobDetail().getJobDataMap().getInt("count");
//int count3 = context.getTrigger().getJobDataMap().getInt("count");
System.err.println("HelloJob is executing. Count: '"+count+"', "+count2+"'");
//The count only gets updated if I updated both the Trigger and
// JobDetail DataMaps. If I only update the JobDetail, it doesn't persist.
context.getTrigger().getJobDataMap().put("count", count++);
context.getJobDetail().getJobDataMap().put("count", count++);
//This has no effect inside the job, but it works outside the job
try {
context.getScheduler().addJob(context.getJobDetail(), true);
} catch (SchedulerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//These don't seem to persist between jobs
//context.put("count", count++);
//context.getMergedJobDataMap().put("count", count++);
}
}
以下是我如何安排这个工作的:
try {
// define the job and tie it to our HelloJob class
JobDetail job = new JobDetail(JOB_NAME, JOB_GROUP_NAME,
HelloJob.class);
job.getJobDataMap().put("count", 1);
// Trigger the job to run now, and every so often
Trigger trigger = new SimpleTrigger("myTrigger", "group1",
SimpleTrigger.REPEAT_INDEFINITELY, howOften);
// Tell quartz to schedule the job using our trigger
sched.scheduleJob(job, trigger);
return job;
} catch (SchedulerException e) {
throw e;
}
更新:
看起来我需要把值放入JobDetail的JobDataMap两次才能使其持久化,这样做有效:
public class HelloJob implements StatefulJob {
public HelloJob() {
}
public void execute(JobExecutionContext context)
throws JobExecutionException {
int count = (Integer) context.getMergedJobDataMap().get("count");
System.err.println("HelloJob is executing. Count: '"+count+"', and is the job stateful? "+context.getJobDetail().isStateful());
context.getJobDetail().getJobDataMap().put("count", count++);
context.getJobDetail().getJobDataMap().put("count", count++);
}
}
这似乎是一个bug,也许?或者我错过了一步,没有告诉JobDetail将其JobDataMap的内容刷新到JobStore中?