6

I am running this quartz-2.1.0\examples\src\main\java\org\quartz\examples\example3 sample code, it runs very well, but if I move the main code in CronTriggerExample.java to a junit test class, the job doesn't run. the following are quartz example code(I truncate them for simplification, you can get full code from quartz website).

SimpleJob.java:

public class SimpleJob implements Job {
  private static Logger _log = LoggerFactory.getLogger(SimpleJob.class);

  public void execute(JobExecutionContext context) throws JobExecutionException {
    JobKey jobKey = context.getJobDetail().getKey();
    _log.info("SimpleJob says: " + jobKey + " executing at " + new Date());
  }
}

CronTriggerExample.java:

public class CronTriggerExample {
    public void run() throws Exception {
        Logger log = LoggerFactory.getLogger(CronTriggerExample.class);
        SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler sched = sf.getScheduler();
        JobDetail job = newJob(SimpleJob.class)
            .withIdentity("job1", "group1")
            .build();
        CronTrigger trigger = newTrigger()
            .withIdentity("trigger1", "group1")
            .withSchedule(cronSchedule("0/3 * * * * ?"))
            .build();

        Date ft = sched.scheduleJob(job, trigger);
        log.info(job.getKey() + " has been scheduled to run at: " + ft
            + " and repeat based on expression: "
            + trigger.getCronExpression());

        sched.start();
    }

    public static void main(String[] args) throws Exception {
        CronTriggerExample example = new CronTriggerExample();
        example.run();
    }
}

the code above runs well, if I move the two lines code in main method to a junit test class(junit4), like this:

public class Test1 {
    @Test
    public void run() throws Exception {
        CronTriggerExample example = new CronTriggerExample();
        example.run();
    }
}

the job doesn't run.

I am very confused why the same code can't run in junit?

1 Answer 1

0

To see the problem by yourself, i advise to run this two different piece of code in debug mode in a IDE like Eclipse.

When you run this two lines in a main, the Quartz Scheduler you create continue running even if the main terminates.

When you run this two lines in JUnit, the JUnit framework kill all the remaining threads when all the unit test are terminated.

To let the time to Quartz to trigger your Job, you should change your JUnit test with the follwing

public class Test1 {
    @Test
    public void run() throws Exception {
        CronTriggerExample example = new CronTriggerExample();
        example.run();

        Thread.sleep(240000); // Sleep 4 minutes (4*60*1.000 = 240.000)
    }
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.