I have a Java application that uses a Quartz Scheduler as a SchedulerFactoryBean . The main() method gets the application context, retrieves the bean root, and runs the scheduling tasks.
The problem is that the scheduler works in its own thread, so when the main thread sends jobs, it returns and the Scheduler continues without it. When the Scheduler is finally complete (or even if you explicitly call shutdown() on it), the application simply hangs there for ages.
I have two solutions:
- Keep track of the number of tasks / triggers, increasing it each time a task is added to the Scheduler. Attach a simple SchedulerListener to the Scheduler, which decreases this count each time
triggerFinalized() called and sets up a while with Thread.sleep() inside it, which constantly checks to see if the count 0 has been deleted. When it does, it will return to the main() , and the application will exit normally. - Take a custom SchedulerListener from option 1 and track the number of jobs inside it. The increment for each call to
jobAdded() and the decrease for each call to triggerFinalized() . When the counter reaches 0, call shutdown() in the Scheduler (or not, it doesn't really matter), and then call System.exit(0) .
In turn, I implemented both of these parameters myself, so I know that they both actually function. The problem is that they are both terrible. Infinite while by polling a value? System.exit(0) ? Bleargh.
Does anyone have a better way, or is this seriously my options?
Edit:. After thinking about this on my way home, I came to the conclusion that this could be due to the fact that I am using SchedulerFactoryBean. It automatically starts when Spring initializes an application context that seems to go beyond the main thread. If I went with a slightly different Scheduler, which I manually initialized and called start() in the code, would this launch the Scheduler in the main thread, blocking it until the Scheduler completed all the tasks? Or will I still have this problem?
Edit: Son ... http://quartz-scheduler.org/documentation/quartz-2.x/examples/Example1
For the program to be able to run the task, we then sleep for 90 seconds. The scheduler runs in the background and must fire the job in these 90 seconds.
Apparently, this will not work, because the scheduler always runs in the background.
source share