TimerTask for scheduling - use Quartz instead.
In most of the web applications there is always a requirement to schedule task which can be repeated on certain interval. For one of our projects, it was required to call a method every fifteen minutes to monitor a table. Initial implementation was done using TimerTask and was a success. Problems arose when we wanted to configure TimerTask in a clustered environment.
A TimerTask once started will create a new Thread of execution. For a clustered environment it would mean configuring different sleep values for all clusters and also the need to test them at least once. Also our implementation was becoming hard to understand for support team who would be responsible for maintaining our application.
Welcome Quartz - From Quartz Web page http://www.opensymphony.com/quartz/
Quartz is a full-featured, open source job scheduling system that can be integrated with, or used along side virtually any J2EE or J2SE application - from the smallest stand-alone application to the largest e-commerce system. Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs; jobs whose tasks are defined as standard Java components or EJBs.
Example for integrating Quartz in a J2EE Application
1. Download Quartz latest release as a zip format from http://www.opensymphony.com/quartz/download.action. From the zip file use quartz-all-<version>.jar which contains almost all the files which are required for Quartz to work.
2. Download Java Transaction API’s (JTA) from http://java.sun.com/products/jta/ which are required by Quartz. Select Class Files to download from the page. This release will be in form of .zip file which has class files inside it. You can extract and again package them as a .jar or leave them as it is.
3. Move Quartz jar and JTA download to WEB-INF/lib directory of your application.
4. Add following lines to your application web.xml to configure Quartz.
- <servlet>
- <display-name>Quartz Initializer Servlet</display-name>
- <servlet-name>QuartzInitializer</servlet-name>
- <servlet-class>
- org.quartz.ee.servlet.QuartzInitializerServlet
- </servlet-class>
- <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>
- <load-on-startup>1</load-on-startup>
- </servlet>
- <servlet>
- <display-name>Scheduler Servlet</display-name>
- <servlet-name>SchedulerServlet</servlet-name>
- <servlet-class>com.test.SchedulerServlet</servlet-class>
- <load-on-startup>2</load-on-startup>
- </servlet>
<servlet> <display-name>Quartz Initializer Servlet</display-name> <servlet-name>QuartzInitializer</servlet-name> <servlet-class> org.quartz.ee.servlet.QuartzInitializerServlet </servlet-class> <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> <load-on-startup>1</load-on-startup> </servlet> <servlet> <display-name>Scheduler Servlet</display-name> <servlet-name>SchedulerServlet</servlet-name> <servlet-class>com.test.SchedulerServlet</servlet-class> <load-on-startup>2</load-on-startup> </servlet>
In the lines above the first Servlet Element defines a new Servlet of typeorg.quartz.ee.servlet.QuartzInitializerServlet which would initialise Quartz at the time of application startup.
The second element defines a new Servlet which would be started as part of Application Init and it is the place from where we configure Quartz.
5. Here is the SchedulerServlet Implementation in which i am configuring a Cron Job. This Cron Job is similar to Unix Cron Job but the difference is that it is managed entirely in Java and does not depend on Unix Cron.
- package com.test;
- import javax.servlet.GenericServlet;
- import javax.servlet.ServletConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import org.quartz.CronExpression;
- import org.quartz.CronTrigger;
- import org.quartz.JobDetail;
- import org.quartz.Scheduler;
- import org.quartz.SchedulerFactory;
- import org.quartz.impl.StdSchedulerFactory;
- import com.test.Worker;
- public class SchedulerServlet extends GenericServlet {
- /**
- * Constant to represent property for the cron expression.
- */
- private static final String CRON_EXPRESSION = “0 0/15 * * * ?”;
- public void init(ServletConfig servletConfig) throws ServletException {
- super.init(servletConfig);
- // The Quartz Scheduler
- Scheduler scheduler = null;
- try {
- // Initiate a Schedule Factory
- SchedulerFactory schedulerFactory = new StdSchedulerFactory();
- // Retrieve a scheduler from schedule factory
- scheduler = schedulerFactory.getScheduler();
- // Initiate JobDetail with job name, job group and
- // executable job class
- JobDetail jobDetail = new JobDetail(“RetryJob”,
- “RetryGroup”, Worker.class);
- // Initiate CronTrigger with its name and group name
- CronTrigger cronTrigger = new CronTrigger(“cronTrigger”,
- “triggerGroup”);
- // setup CronExpression
- CronExpression cexp = new CronExpression(CRON_EXPRESSION);
- // Assign the CronExpression to CronTrigger
- cronTrigger.setCronExpression(cexp);
- // schedule a job with JobDetail and Trigger
- scheduler.scheduleJob(jobDetail, cronTrigger);
- // start the scheduler
- scheduler.start();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public void service(ServletRequest serveletRequest, ServletResponse servletResponse)
- throws ServletException, IOException {
- }
- }
package com.test;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import com.test.Worker;
public class SchedulerServlet extends GenericServlet {
/**
* Constant to represent property for the cron expression.
*/
private static final String CRON_EXPRESSION = "0 0/15 * * * ?";
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
// The Quartz Scheduler
Scheduler scheduler = null;
try {
// Initiate a Schedule Factory
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
// Retrieve a scheduler from schedule factory
scheduler = schedulerFactory.getScheduler();
// Initiate JobDetail with job name, job group and
// executable job class
JobDetail jobDetail = new JobDetail("RetryJob",
"RetryGroup", Worker.class);
// Initiate CronTrigger with its name and group name
CronTrigger cronTrigger = new CronTrigger("cronTrigger",
"triggerGroup");
// setup CronExpression
CronExpression cexp = new CronExpression(CRON_EXPRESSION);
// Assign the CronExpression to CronTrigger
cronTrigger.setCronExpression(cexp);
// schedule a job with JobDetail and Trigger
scheduler.scheduleJob(jobDetail, cronTrigger);
// start the scheduler
scheduler.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void service(ServletRequest serveletRequest, ServletResponse servletResponse)
throws ServletException, IOException {
}
}
Code above creates a Cron Job which will call Worker ( which implements Job) and calls its execute method. There are numerous types of triggers which can be created and CronTrigger is just one example.6. Worker class which implements Job Interface
- package com.test;
- import org.quartz.Job;
- import org.quartz.JobExecutionContext;
- import org.quartz.JobExecutionException;
- /**
- * worker thread
- */
- public class Worker implements Job {
- public void execute(JobExecutionContext context)
- throws JobExecutionException {
- System.out.println(“Put task to be executed here”);
- }
- }
package com.test;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
/**
* worker thread
*/
public class Worker implements Job {
public void execute(JobExecutionContext context)
throws JobExecutionException {
System.out.println("Put task to be executed here");
}
}
Simple isn’t it.
|
|
|
Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.


Comments
No comments yet.
Leave a comment