Tuesday, October 12, 2010

Java Scheduling with Quartz and Spring

I have recently been involved with scheduling background jobs in a Java Enterprise application. I had the Choice of using java Executer framework support, Timer class from Java and Quartz.
I Went with Quartz because of the simple fact that they have separated out triggers from the Job. In my case i wanted multiple scheduling time for the same job(I know sychronization can be bit of a pain).  If you go through the tutorial on the Website for Quartz's http://www.opensymphony.com/quartz you will realize it is rather easy to set up the package and make it work. All the threads that you needed to create (Executor Factories in case of JDK 5.0) are gone, which was really nice.

Here's what i did....
   created a job class using the spring wrapper for quartz's e.g.
Public class FooJob extends QuartzJobBean{

       public void executeInternal (JobExecutionContext context) {
                System.out.println("Did my Foo job.... what about you?");

This is the as simple a class can get, with just a print statement, of course your job would me much more complex (which was my case ) but the basic idea remains.

What Springs philosophy says that you should only write code which is related to the job in hand and should not be bothered about the Triggers that you need and how they would be attached with the Job. Keeping that in mind, after writing this Job class you need to switch to the spring configurations.

First things first we need to declare this Job class as our bean class(Did you notice the name "Bean" in the class extended ;) )

< bean id="fooJob" class="org.springframework.scheduling.quartz.JobDetailBean">

That's it, now you can create a main class which creates a ApplicationContext and you are done!

Of course there are many more things you can do with this but on that in later posts...

No comments: