查找作业是否在Quartz1.6中运行

Mar*_*ina 12 quartz-scheduler

我想澄清Quartz1.6中scheduler.getCurrentlyExecutingJobs()方法的细节.我有一份工作,在任何特定时刻都应该只运行一个实例.它可以被触发从UI"立即运行",但如果已经为此作业运行的作业实例 - 什么都不应该发生.

这就是我如何检查是否有一个让我感兴趣的工作:

    List<JobExecutionContext> currentJobs = scheduler.getCurrentlyExecutingJobs();
    for (JobExecutionContext jobCtx: currentJobs){
    jobName = jobCtx.getJobDetail().getName();
    groupName = jobCtx.getJobDetail().getGroup();
    if (jobName.equalsIgnoreCase("job_I_am_looking_for_name") &&
        groupName.equalsIgnoreCase("job_group_I_am_looking_for_name")) {
        //found it!
        logger.warn("the job is already running - do nothing");
    }               
}
Run Code Online (Sandbox Code Playgroud)

然后,为了测试这个,我有一个单元测试,试图一个接一个地安排这个工作的两个实例.我希望在尝试安排第二份工作时看到警告,相反,我得到了这个例外:

org.quartz.ObjectAlreadyExistsException: Unable to store Job with name:
 'job_I_am_looking_for_name' and group: 'job_group_I_am_looking_for_name', 
 because one already exists with this identification.
Run Code Online (Sandbox Code Playgroud)

当我在调试模式下运行此单元测试时,此行中断:

列出currentJobs = scheduler.getCurrentlyExecutingJobs();

我看到列表是空的 - 因此调度程序不会将此作业视为正在运行,但它仍然无法再次安排它 - 这告诉我当时工作确实正在运行...

我用这种调度方法错过了一些更好的观点吗?

谢谢!

码头

Mar*_*ina 18

对于其他人的利益,我张贴的答案,我是有这个问题-我从兵马俑论坛泽棉邓帮助:张贴在兵马俑论坛

这是重新上限:对正在运行的工作的实际检查工作正常 - 当然,这只是单元测试的时间.我已经在工作中添加了一些睡眠,并调整了单元测试以安排第二个工作,而第一个工作仍在运行 - 并且验证我确实可以找到第一个工作仍在运行.

我得到的例外是因为我试图安排一个具有相同名称的新作业,而不是尝试触发已经存储在调度程序作业中的作业.以下代码完全按照我的需要工作:

List<JobExecutionContext> currentJobs = scheduler.getCurrentlyExecutingJobs();
for (JobExecutionContext jobCtx: currentJobs){
    jobName = jobCtx.getJobDetail().getName();
    groupName = jobCtx.getJobDetail().getGroup();
    if (jobName.equalsIgnoreCase("job_I_am_looking_for_name") && groupName.equalsIgnoreCase("job_group_I_am_looking_for_name")) {
        //found it!
        logger.warn("the job is already running - do nothing");
                 return;
    }               
}
      // check if this job is already stored in the scheduler
JobDetail emailJob;
emailJob = scheduler.getJobDetail("job_I_am_looking_for_name", "job_group_I_am_looking_for_name");
if (emailJob == null){
       // this job is not in the scheduler yet
  // create JobDetail object for my job 
  emailJob = jobFactory.getObject();
  emailJob.setName("job_I_am_looking_for_name");
  emailJob.setGroup("job_group_I_am_looking_for_name");
  scheduler.addJob(emailJob, true);             
}

// this job is in the scheduler and it is not running right now - run it now
scheduler.triggerJob("job_I_am_looking_for_name", "job_group_I_am_looking_for_name");
Run Code Online (Sandbox Code Playgroud)

谢谢!码头