Search code examples
javaquartz-scheduler

Quartz jobdetail from jobkey is null


I have following two methods,

initialJob();
otherJobs();

Others jobs only need to start once the initial job is complete.

This is the initial job method.

private void initialJob(){
JobDetail jobDetail = JobBuilder.newJob(RestTriggerForQuartzJobs.class)
                          .withIdentity("INITIAL_JOB_NAME", TRIGGER_GROUP)
                          .usingJobData("PARAM", "")
                          .build();               
   Trigger trigger = TriggerBuilder.newTrigger().forJob(jobDetail).startNow().build();
   scheduler.scheduleJob(jobDetail, trigger);
}

Here I am checking if the initial job is completed. If not, calling the same method recursively till it completes

private void otherJobs(){
   if(isJobComplete("INITIAL_JOB_NAME")){
   JobDetail jobDetail = JobBuilder.newJob(RestTriggerForQuartzJobs.class)
                          .withIdentity("JOB_NAME", TRIGGER_GROUP)
                          .usingJobData("PARAM", "")
                          .build();               
   Trigger trigger = TriggerBuilder.newTrigger().forJob(jobDetail).startNow().build();
   scheduler.scheduleJob(jobDetail, trigger);
   }else{
   otherJobs();
   }
}

In isComplete Method, jobDetail is getting null for JobDetail jobDetail = scheduler.getJobDetail(jobKey) eventhough I can see the DEFAULT.INITIAL_JOB_NAME in the quartz triggers table.

private Boolean isJobComplete(String jobName) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobDetail.getKey());
        for (Trigger trigger : triggers) {
            TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
            if (TriggerState.COMPLETE.equals(triggerState)) {
                return true;
            }
        }
        return false;
    }

Solution

  • The method scheduler.getJobDetail(jobKey) is returning null because JobKey is composed of both name and group in order to uniquely identify a job.

    That means you have to initiate your JobKey with both name and group:

    private Boolean isJobComplete(String jobName) throws SchedulerException {
        JobKey jobKey = new JobKey(jobName, TRIGGER_GROUP);
        JobDetail jobDetail = scheduler.getJobDetail(jobKey);
        ...
    

    Another tip by the way: Calling the method otherJobs recursively an undefined time could lead to a StackOverflowError. Maybe listeners are useful for your use case.