Posts Tagged ‘Quartz’

Quartz, Java Scheduler

Thursday, May 13th, 2010
Quartz is a robust, flexible tool, it can be used to accomplish simple to complex job scheduling. Quartz can create a simple or complex schedule from a simple Java stand alone application to large e-commerce systems. It has complete support for creating jobs based on crontab-like syntax. This API allows you to schedule tasks within your own application, which means that you’re more or less free to control the scheduling in your way. There are many and easy ways available to configure the Quartz.
Better than Cron Jobs with Java
Quartz is better solution than working with system’s cron job calling the java methods directly, because if we are going to make any changes to environment variables, then it may affect the cron which is calling a java method. And since java is platform independent, porting the crons between the operating system will not be easier. There is some security issues related to this also because this allows the user to provide the input outside of the JVM. Scheduler
Components
The major components of the quartz are Jobs and Triggers. These are interrelated. The Job in the Quartz defines what should be executed as part of the scheduling and a Trigger defines when these jobs have to be executed. Quartz provides us the flexibility of assigning the same job to a number of triggers and vice versa. These combinations are managed by a scheduler, which takes care of all the boring details like working out priorities, and calling the jobs when they’re due.
Defining a Job
Defining a Job will be very simple; we just need to implement a “Job” interface from the framework. And this class has to implement the deferred method “execute”. And this execute method has an argument called “JobExecutionContext”, which provides the job’s context info like, the last run and the next run. This job implementation defines your business logic, which has to be executed on a regular basis. This job implementation will be made useful by registering with the class JobDetail. This is done by using the following code,
		JobDetail job = new JobDetail("demo",demoGroup, MyDemo.class);
	
The JobDetail constructor takes three arguments, the first defines the name of the Job, the second one defines the group of the Job and third one takes the class of our job implementation. The job name is unique along with the group within a Scheduler.
Triggers
Jobs are nothing to do with if we are not having any trigger associated with. You create a trigger and associate it with a job when registering the job with the Scheduler. There are four types of Quartz triggers are available, but two main types are used most often; they are SimpleTrigger and CronTrigger.
A SimpleTrigger is the simpler of the two and is used primarily to fire single event jobs. This trigger fires at a given time, repeats for n number of times with a delay of m between each firing, and then quits. The following code snippet shows how to create an SimpleTrigger,
		SimpleTrigger trigger = new SimpleTrigger();
		trigger.setName("mySimpleTrigger");
		trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
		trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
		trigger.setRepeatInterval(60L*1000L);
	
The CronTriggers are much more complicated and powerful. They are based on the common Gregorian calendar and are used when you need to execute a job with a more complicated schedule. The simple way of creating the CronTrigger is,
			CronTrigger trigger = new CronTrigger();
			trigger.setName("myCronTrigger");
			trigger.setCronExpression("0/30 * * * * ?");
	
Scheduler
Once we are done with the job implementation and the triggers, we can tag this job with the scheduler, so that it’ll be on its business. Quartz provides us the mechanism to attach these jobs with scheduler through the “SchedulerFactory” class. So if we are going to make use of the Quartz in our application, we have to initialize the scheduler and start it. This can be done through any of the servlet class if it’s a web application. The following piece of code will be executed for that purpose.
			SchedulerFactory schedulerFactory = new StdSchedulerFactory();
			Scheduler scheduler = schedulerFactory.getScheduler();
			scheduler.start();
	
Now we are done with the scheduler, we can schedule a job with this scheduler object. The code as follows
		scheduler.scheduleJob(job,schedule);
	
Job Stores
Job Stores are the place, where Quartz used to store the status of all the jobs. JobStores are internal to Quartz framework, so we just need to instruct the framework to use any of the JobStores depends upon our requirement and pattern of the application in which we use the framework.Quartz allows two types of JobStores, they are

  • Memory Storage – The details of the jobs will be stored into RAM. This gives us the flexibility of accessing these information fast, but the only problem here is if the machine gets restarted, then we’ll loose all of these information.
  • Persistence Storage – The information will be stored into a permanent place like databases, Quartz will provide the mechanism to access these information through the JDBC.
Quartz Listeners
Listeners provide a convenient mechanism for getting notified when certain events of interest occur. Quartz provides three types of listeners: one for Jobs, one for Triggers, and one for the Scheduler itself. The listener is an extension point in the Quartz framework, so the developers must be implementing these listeners and does a simple customization for using it.
Implementing Listeners in Quartz
There are three steps to be followed to implement a listener for any of the above said Listeners.

  • A Class which implements the Listener Interface.
  • Methods of the Listener Interface should be implemented.
  • Finally register this Listener.

As mentioned earlier listeners can be implemented any of the Quartz components, Quartz framework provides there different interface for the above purpose. They are JobListener, TiggerListener and SchedulerListener.

The main reasons for using listeners in Quartz are,

  • Sending an e-mail after successful completion of a job.
  • Scheduling other jobs based on successful or failed completion of a job.
  • Recording the actual time a job runs
Implementing Quartz into our Web Application(s)
There are numerous ways to configure the Quartz for your application running on a Web Container. We can have a custom Servlets to initialize the scheduler engine, i.e each Job we are having in our application we’ll have a Servlet to start the Scheduler engine. But the best practice would be making use of the “QuartzInitializerServlet” Servlet provided by Quartz framework, which will help us doing the above job. The Servlet will be configured like the following in web.xml
		<servlet>
		<servlet-name>QuartzInitializer</servlet-name>
		<display-name>Quartz Initializer Servlet</display-name>
		<servlet-class>org.quartz.ee.servlet.QuartzInitializerServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
			<init-param>
			<param-name>config-file</param-name>
			<param-value>quartz.properties</param-value>
		</init-param>
		<init-param>
			<param-name>shutdown-on-unload</param-name>
			<param-value>true</param-value>
		</init-param>
		<init-param>
			<param-name>start-scheduler-on-load</param-name>
			<param-value>true</param-value>
		</init-param>
	</servlet>
	
From the above said configuration we are instructing the container to refer the properties from quartz.properties.The quartz.properties will have the following settings,
			org.quartz.plugin.jobInitializer.class=org.quartz.plugins.xml.JobInitializationPlugin
			org.quartz.plugin.jobInitializer.fileNames = quartz-config.xml
			org.quartz.plugin.jobInitializer.overWriteExistingJobs = true
			org.quartz.plugin.jobInitializer.failOnFileNotFound =true
			org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
			org.quartz.threadPool.threadCount = 5
			org.quartz.threadPool.threadPriority = 5
	
In the above property mentioned Threadcount controls the number of quartz threads dedicated to the engine. Threadpriority 5 means normal priority, while priority 1 is highest priority.Apart from these configurations, if we look at the properties file, we have another configuration file called “quartz-config.xml”. This allows the developer to mention the jobs and trigger details. This will be useful when we are using the QuartzInitializerServlet for starting the scheduler engine. The following code shows how to configure a Jobs and Triggers using an XML.
		<quartz>
			<job>
				<job-detail>
					<name>myDemoScheduler</name>
					<group>myCrons</group>
					<description>Demo Job for KShop</description>
					<job-class>com.infy.Scheduler</job-class>
					<volatility>false</volatility>
					<durability>false</durability>
					<recover>false</recover>
				</job-detail>
				<trigger>
					<cron>
						<name>scheduler-trigger</name>
						<group>scheduler-triggers</group>
						<job-name>myDemoScheduler</job-name>
						<job-group>myCrons</job-group>
						<cron-expression>0 0/5 * * * ?</cron-expression>
					</cron>
				</trigger>
			</job>
		</quartz>
	
Download
To download the Quartz Examples Click Here
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Get Adobe Flash player