Do I need to shutdown Quartz scheduler in finally block?
-
29-10-2019 - |
Question
I am using Quartz 2.0.1 scheduler from StdSchedulerFactory
.
I am catching SchedulerException
in my code.
Should I shutdown the scheduler in a finally block:
} finally {
scheduler.shutdown();
}
or should I do the shutdown in the try block?
The shutdown method can throw SchedulerException
, so it seems the shutdown should not be in the finally block.
Solution
You don't have to do it in the finally block in any case because if the scheduler is started successfully it won't throw the SchedulerException
and hence if you are reaching the catch block of SchedulerException
that means the scheduler was never started. So, you should not shutdown a scheduler that is never started.
Here is a sample program from the project homepage.
public class QuartzTest {
public static void main(String[] args) {
try {
// Grab the Scheduler instance from the Factory
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
// and start it off
scheduler.start();
scheduler.shutdown();
} catch (SchedulerException se) {
se.printStackTrace();
}
}
}
Also, from the above link,
Once you obtain a scheduler using StdSchedulerFactory.getDefaultScheduler(), your application will not terminate until you call scheduler.shutdown(), because there will be active threads.
OTHER TIPS
Riffing on the above answer, it may still run into problems if there is other code than the start/shutdown. For example if you have something like this:
public class QuartzTest {
public static void main(String[] args) {
try {
// Grab the Scheduler instance from the Factory
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
// and start it off
scheduler.start();
System.out.println(args[5]);
scheduler.shutdown();
} catch (SchedulerException se) {
se.printStackTrace();
}
}
}
The application will never call shutdown because you'll end up with an ArrayIndexOutOfBoundsException (or something like that). There are quite a few ways to solve this, but this simplest would likely be to wrap all intermediate code in an exception handler and "handle" things there. For example: public class QuartzTest {
public static void main(String[] args) {
try {
// Grab the Scheduler instance from the Factory
Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
// and start it off
scheduler.start();
try {
System.out.println(args[5]);
} catch (Exception e) {
e.printStackTrace();
}
scheduler.shutdown();
} catch (SchedulerException se) {
se.printStackTrace();
}
}
}