Create Free Blog | Random Blog »   Report Abuse | Login   

 

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.

  1. <servlet>
  2. <display-name>Quartz Initializer Servlet</display-name>
  3. <servlet-name>QuartzInitializer</servlet-name>
  4. <servlet-class>
  5. org.quartz.ee.servlet.QuartzInitializerServlet
  6. </servlet-class>
  7. <init-param>
  8. <param-name>shutdown-on-unload</param-name>
  9. <param-value>true</param-value>
  10. </init-param>
  11. <init-param>
  12. <param-name>start-scheduler-on-load</param-name>
  13. <param-value>true</param-value>
  14. </init-param>
  15. <load-on-startup>1</load-on-startup>
  16. </servlet>
  17. <servlet>
  18. <display-name>Scheduler Servlet</display-name>
  19. <servlet-name>SchedulerServlet</servlet-name>
  20. <servlet-class>com.test.SchedulerServlet</servlet-class>
  21. <load-on-startup>2</load-on-startup>
  22. </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.

  1. package com.test;
  2. import javax.servlet.GenericServlet;
  3. import javax.servlet.ServletConfig;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.ServletRequest;
  6. import javax.servlet.ServletResponse;
  7. import org.quartz.CronExpression;
  8. import org.quartz.CronTrigger;
  9. import org.quartz.JobDetail;
  10. import org.quartz.Scheduler;
  11. import org.quartz.SchedulerFactory;
  12. import org.quartz.impl.StdSchedulerFactory;
  13. import com.test.Worker;
  14. public class SchedulerServlet extends GenericServlet {
  15. /**
  16. * Constant to represent property for the cron expression.
  17. */
  18. private static final String CRON_EXPRESSION = “0 0/15 * * * ?”;
  19. public void init(ServletConfig servletConfig) throws ServletException {
  20. super.init(servletConfig);
  21. // The Quartz Scheduler
  22. Scheduler scheduler = null;
  23. try {
  24. // Initiate a Schedule Factory
  25. SchedulerFactory schedulerFactory = new StdSchedulerFactory();
  26. // Retrieve a scheduler from schedule factory
  27. scheduler = schedulerFactory.getScheduler();
  28. // Initiate JobDetail with job name, job group and
  29. // executable job class
  30. JobDetail jobDetail = new JobDetail(“RetryJob”,
  31. “RetryGroup”, Worker.class);
  32. // Initiate CronTrigger with its name and group name
  33. CronTrigger cronTrigger = new CronTrigger(“cronTrigger”,
  34. “triggerGroup”);
  35. // setup CronExpression
  36. CronExpression cexp = new CronExpression(CRON_EXPRESSION);
  37. // Assign the CronExpression to CronTrigger
  38. cronTrigger.setCronExpression(cexp);
  39. // schedule a job with JobDetail and Trigger
  40. scheduler.scheduleJob(jobDetail, cronTrigger);
  41. // start the scheduler
  42. scheduler.start();
  43. catch (Exception e) {
  44. e.printStackTrace();
  45. }
  46. }
  47. public void service(ServletRequest serveletRequest, ServletResponse servletResponse)
  48. throws ServletException, IOException {
  49. }
  50. }
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

  1. package com.test;
  2. import org.quartz.Job;
  3. import org.quartz.JobExecutionContext;
  4. import org.quartz.JobExecutionException;
  5. /**
  6. * worker thread
  7. */
  8. public class Worker implements Job {
  9. public void execute(JobExecutionContext context)
  10. throws JobExecutionException {
  11. System.out.println(“Put task to be executed here”);
  12. }
  13. }
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.

Share SocialTwist Tell-a-Friend 
Generated Keywords for the page : rose quartz , quartz crystal , quartz , , quartz jar , org quartz crontrigger , quartz properties file , spring quartz applicationcontext , tomcat quartz , quartz j2ee , quartz scheduler examples , tutorial quartz , quartz webapp , rose quartz rings , gold quartz earrings , quartz jewellery , quartz rings , rose quartz bracelets , rose quartz jewellery , quartz crystal pendants , quartz heaters , quartz jewelry , quartz tube , rose quartz bead , rose quartz beads , rose quartz jewelry , semiconductor quartz , clear quartz crystals , lemon quartz cabochon , polished quartz , quartz beaker , quartz clock movement , quartz counters , quartz infrared heater , quartz infrared heaters , quartz pendant , rose quartz bracelet , arkansas quartz crystal , lemon quartz , mystic quartz , quartz analog watches , quartz cells , quartz clock movements , quartz counter , quartz countertop , quartz crystal jewelry , quartz granite countertops , quartz halogen , quartz heater , quartz hill storage , quartz infrared heating , quartz instruments , quartz natural stone , quartz oscillators , quartz product ,

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

(required)

(required)


*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-Spam Image