Quartz Scheduler Framework in Java and Integration With Spring Example

In my previous post as we had already discussed basics of Quartz Scheduler Framework ,what are the main components of it and why Quartz Scheduler Framework is so popular across the industry for the jobs where scheduling comes into picture. If you have missed that post you can read it here.

In this post we are going to do our hands dirty as we will do some basic scheduling programming and then we will see how we can integrate quartz and spring. So, first let’s take a look at the perquisites . Here , for this example I am going to use Maven for creating a module and to take care of its dependencies.

Assumption : You are familiar with Spring framework and specifically with dependency injections , so that you can understand each and every step in Quartz and Spring Integration.

1.       Dependencies :   Below is the quartz maven coordinates that you have to add in your pom file , so that we can integrate Quartz and Spring. For our example only 1st dependency is required , but other will also come into play when we will write some complex programs.

Now we will write our first component for the framework i.e Job (task that you want to get executed at a particular time interval with a specific frequency ).


    org.quartz-scheduler
    quartz
    2.2.0


    org.quartz-scheduler
    quartz-oracle
    2.2.0


    org.quartz-scheduler
    quartz-weblogic
    2.2.0


    org.quartz-scheduler
    quartz-jboss
    2.2.0

2.       Quartz Job :

A Job can be any class that will extend from QuartzJobBean and will override the execute method. In my example , job sole responsibility is to send the email to the administrator with the details of blocked sites visited by company employees. Detail will comprise of three things – Website address , User system IP from which it was originated , and frequency.  I am not going to write the actual code logic for this  here , but if anybody needs it I can help him out on this logic.

So, my class that is going to this job is TrackUserActivity.

Note : It is not related to Quartz Framework , it can be anything specific to your application. Only importance of this class is it is going to  use in our scheduler job.

package com.lotusmedia.code.quartz;

public class TrackUserActivity extends Activity{

    public List getActivity(){
	 List activityList=new ArrayList();

	 /**
	 *   Business logic will go here that will fetch the activityList.
	 *
	 **/

	 return activityList;
	}

}

So, now we are ready to create our job that will internally use this TrackUserActivity to get the information and send an email.

SendEmailToAdmin.java :

package com.lotusmedia.code.quartz;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.mail.MessagingException;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.QuartzJobBean;

public SendEmailToAdmin extends QuartzJobBean{

		 @AutoWired
         TrackUserActivity trackUserActivity;

		 public void setTrackUserActivity(TrackUserActivity trackUserActivity){
		 this.trackUserActivity=trackUserActivity;
		 }

		 @Override
         protected void executeInternal(JobExecutionContext context) throws JobExecutionException{
		 List<Activity> activityList=trackUserActivity.getActivity();

		 /**
		 *  Business Logic for fethcing data from activityList and sending email will go here.
		 *
		 /
		 Email email = new Email();
         email.setFrom("no-reply@lotusmediacentre.com");
         email.setSubject("Users Activity Details");
         email.setTo("admin@lotusmediacentre.com");
		// will populate the text with website address, ip address and frequency in the HTML Table format.
		// I am skipping that as it will take unnecessary space.
        // email.setText("");

		//This method is available in one of the helper class.
		   sendEmail(email).
		 }
}

Now its turn to configure this job in our application context file.

<bean id="trackUserActivity" class="com.lotusmedia.code.quartz.TrackUserActivity"></bean>

<bean name="sendEmailToAdmin" class="org.springframework.scheduling.quartz.JobDetailBean">

	<property name="jobClass" value="com.lotusmedia.code.quartz.SendEmailToAdmin" />

	<property name="jobDataAsMap">
		<map>
			<entry key="trackUserActivity" value-ref="trackUserActivity" />
		</map>
	</property>

</bean>

3.  Trigger
So, its time to write our second component i.e Trigger. For my example I am going to use Cron    Trigger that will fire the job at every day 12:00 AM.

<bean id="cronTrigger" 	class="org.springframework.scheduling.quartz.CronTriggerBean"> 
		<property name="jobDetail" ref="sendEmailToAdmin" />
		<property name="cronExpression" value="0 0 12 * * ?" /> 
</bean>

4.       Scheduler :
Its time to write our final component i.e Scheduler and its sole responsibility is to integrate the job and trigger.

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
	<property name="jobDetails">
	   <list>
	      <ref bean="sendEmailToAdmin" />
	   </list>
	</property>

	<property name="triggers">
	    <list>
		<ref bean="cronTrigger" />
	    </list>
	</property>
   </bean>

5.       Final Configuration File – spring-job.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="trackUserActivity" class="com.lotusmedia.code.quartz.TrackUserActivity"></bean>

    <bean name="sendEmailToAdmin" class="org.springframework.scheduling.quartz.JobDetailBean">

	<property name="jobClass" value="com.lotusmedia.code.quartz.SendEmailToAdmin" />

	<property name="jobDataAsMap">
		<map>
			<entry key="trackUserActivity" value-ref="trackUserActivity" />
		</map>
	</property>

</bean>

<bean id="cronTrigger" 	class="org.springframework.scheduling.quartz.CronTriggerBean"> 
		<property name="jobDetail" ref="sendEmailToAdmin" />
		<property name="cronExpression" value="0 0 12 * * ?" /> 
</bean>

 <bean id="scheduler" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
	<property name="jobDetails">
	   <list>
	      <ref bean="sendEmailToAdmin" />
	   </list>
	</property>

	<property name="triggers">
	    <list>
		<ref bean="cronTrigger" />
	    </list>
	</property>
   </bean>

</beans>


6.       Unit Test :

When you deployed this application , it will start sending emails everyday at the specified time. If you want you can also write a unit test to check the functionality .
Note : While doing unit testing change the cron expression , so that you can see the output at the same time instead of waiting till 12:00 in the night.
So, here we have completed the Quartz integration with Spring and we have also seen an example that can give atleast basic idea on the components.

Drop me a comment , if you are facing any problem in any of the step or if you need any specific information. I will be glad to help you .

Happy Scheduling :)

Let'sConnect

Saurabh Jain

A Developer working on Enterprise applications ,Distributed Systems, Hadoop and BigData.This blog is about my experience working mostly on Java technologies ,NoSQL ,git , maven and Hadoop ecosystem.
Let'sConnect

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

10 thoughts on “Quartz Scheduler Framework in Java and Integration With Spring Example

  1. Pingback: boutique moncler
Add Comment Register



Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>