Search code examples
javaquartz

Scheduler.triggerJob does not trigger the job


I am trying to execute my quartz jobs in tests but they do not seem to be triggered. The 'runJob()' is never executed. No exceptions, no errors on logs. What am I missing? Any ideas?

@Autowired
Scheduler scheduler;

@Test
@Transactional
public void MyJobTest() {
    //Create a new Job
    JobKey jobKey = JobKey.jobKey(MyJob.class.getSimpleName(), JobGroupEnum.GROUP1.getName());
    JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity(jobKey).storeDurably(true).build();
    try {
        scheduler.addJob(job, true); //Register this job to the scheduler
        scheduler.triggerJob(job.getKey()); //Immediately trigger the Job
    } catch (Exception e) {
        e.printStackTrace();
    }
}

And here are the logs:

Starting Quartz Scheduler now
Scheduler quartzScheduler_$_NON_CLUSTERED started.
Started MyJobTest in 20.965 seconds (JVM running for 22.537)
Began transaction (1) for test context [DefaultTestContext@704deff2 testClass = MyJobTest, testInstance = ....
Rolled back transaction for test: [DefaultTestContext@704deff2 testClass = MyJobTest, testInstance = ....
Scheduler quartzScheduler_$_NON_CLUSTERED paused.
Shutting down ExecutorService 'applicationTaskExecutor'
Shutting down Quartz Scheduler
Scheduler quartzScheduler_$_NON_CLUSTERED shutting down.
Scheduler quartzScheduler_$_NON_CLUSTERED paused.
Scheduler quartzScheduler_$_NON_CLUSTERED shutdown complete.

Solution

  • (Based on comment suggestion Quartz example)

    Adding the following lines after the triggerJob() made it work:

    Thread.sleep(2L * 1000L); //sleep for 2 seconds so scheduler has time to fire off the job
    scheduler.shutdown(true); //passing true tells the Quartz Scheduler to wait until all jobs have completed running