javakotlinquartz-schedulerjobsdropwizard

How can I manually trigger a job via dropwizard-jobs


We have jobs set up for our dropwizard project via the dropwizard jobs library. We want to add some functionality to allow to us to trigger these jobs manually. Does anyone know how to do this?

If there is no way to do this, is there some way that we could use the underlying quartz scheduler library to trigger the jobs? It should be noted that we are using hk2 dependency injection. So our job classes have dependencies passed into them.

Here is a link to the dropwizard-jobs library: https://github.com/dropwizard-jobs/dropwizard-jobs

I have tried wrapping the jobs classes that we have (that were designed for the dropwizard jobs framework) in classes that implement thr Job interface from the quartz library, and then I have tried the following code to execute them.

// Create a new Job 
JobKey jobKey = JobKey.jobKey("myNewJob", "myJobGroup");
JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity(jobKey).storeDurably().build();

// Register this job to the scheduler
scheduler.addJob(job, true);

// Immediately fire the Job MyJob.class
scheduler.triggerJob(jobKey);

However, the job never seems to run. Even when debugging, I'm seeing that the breakpoints for the code inside the job are never hit. I only ever saw them being hit once and that was during a debugging sessions, but so far, have been unable to replicate that behavior.

This leads me to think that the jobs are misfiring. But I don't have much experience with quartz or dropwizard-jobs, so am unsure how to debug/troubleshoot or what the underlying cause could be. I'm wondering if the cause could be that the MyJob.class we are using, uses hk2 dependency injection, and perhaps we are unable to invoke the job like this as a result. But I'm not sure


Solution

  • I figured out how to do this. You can use the underlying Quartz Scheduler.

    You can instantiate the implementation of the StdSchedulerFactory and then call getAllSchedulers and then you can look through the list to find one that is started and the list of job group names is not empty.

    Like this for example:

    Scheduler scheduler = new StdSchedulerFactory().getAllSchedulers().stream().filter(schedulerToCheck -> {
        try {
            return schedulerToCheck.isStarted() && !schedulerToCheck.getJobGroupNames().isEmpty();
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }).collect(Collectors.toList()).get(0);
    

    Now that you have the scheduler, you can get the job keys for its scheduled jobs and trigger them using the scheduler itself. You can iterate through the job groups returned by getJobGroupNames() and call the getJobKeys() function to get the keys. See How to query the scheduled jobs from Quartz scheduler?