Saturday, March 19, 2011

Quartz Framework: Implementation with Jsp-Servlet

Other Links: Job Scheduling with java.util.Timer
                    Job Scheduling with Quartz Framework and JSP - Servlet
                    Job Scheduling with Quartz Framework and Java Spring Framework




Quartz is a full-featured, open source job scheduling service that can be integrated with, or used along side virtually any Java EE or Java SE 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 that may execute virtually anything you may program them to do. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering. Quartz is freely usable, licensed under the Apache 2.0 license.
The download link for Quartz is located on the main Quartz page (www.opensymphony.com/quartz).  Important jar files to be used with Quartz framework are: a) Common BeanUtils b) Common Collections c) Common Digester d) Common Logging e) Quartz.jar
Important Features of Quartz:
1)      Ability to run in different runtime environments like application server, web containers, clusters of standalone programs, etc.
2)      Ability to schedule tasks for a specific time or at a specific time interval. Even, you can block tasks for a specific time.
3)      Allows organizing triggers as groups in the scheduler.
4)      Allows associating multiple jobs with the same trigger.
5)      Includes event handlers to demarcate start and finish
points of a triggered job.
6)      Allows configuration to automatically re-trigger a job if it
fails.
7)      Allows configuring jobs to participate in JTA transactions.
8)      Allows to store jobs and triggers in a database, file, or
cache them in memory.
9)      Supports fail-over and load balancing.
10)  Provides listener support to monitor scheduled jobs from
any application.

Please click on any advertisement if you like this blog.
Quartz Tour: Lets do a tour to quartz framework to keep ourselves safe from our girl friends (for clarification of this, please go through my previous post).
Note: Here, I am going to give very brief idea about some important terminology. For more information, please refer some materials like “Quartz Job Scheduling Framework by Chuck Cavaness”
Ø      Quartz Schedular
Ø      Quartz Jobs
Ø      Triggers (Cron trigger and simple trigger both)
Ø      Job Store
Quartz Schedular: It manages the run time environment of the Quartz framework. When schedular starts, it initializes the threads and waits for the task to be triggered. Schedular’s queue is used to schedule the task in queue.
Jobs: Jobs are simply java class that perform certain task. It must implement org.quartz.Job interface and throws org.quartz.JobExecutionException. We must override the execute method and it is the place where we will put our logic to be run.
Triggers: Triggers define when a job should be fired. There are 2 types of triggers:
a)      Cron trigger: It can define a very complex timing for firing of the job. It may define on which time on which day in which weak of which month of which year, the job should be executed.
b)     Simple Trigger: It is used to define the simple time line for jobs like to fire job on a specified time and to repeat the job after given time intervals.
Job Store: Quartz provides an interface for all types of job storage. The interface located in the org.quartz.spi package is called JobStore. All job storage mechanisms, regardless of where or how they store their information, must implement this interface. Quartz users almost never access or see concrete classes that implement the JobStore interface; they are used internally by the Quartz Scheduler to retrieve job and trigger information during runtime.
In quartz framework there is a defined way of defining the duration at which the job should be executed. This duration is defined with the help of an expression i.e. called as the cron expression:
Cron Expression: Cron-Expressions are strings that are actually made up of seven sub-expressions, that describe individual details of the schedule. These sub-expression are separated with white-space, and represent:
  1. Seconds
  2. Minutes
  3. Hours
  4. Day-of-Month
  5. Month
  6. Day-of-Week
  7. Year (optional field)
Please click on any advertisement if you like this blog.

Example of Cron Expression:
Expression
Meaning
0 0 12 * * ?
Fire at 12pm (noon) every day
0 15 10 ? * *
Fire at 10:15am every day
0 15 10 * * ?
Fire at 10:15am every day
0 15 10 * * ? *
Fire at 10:15am every day
0 15 10 * * ? 2005
Fire at 10:15am every day during the year 2005
0 * 14 * * ?
Fire every minute starting at 2pm and ending at 2:59pm, every day
0 0/5 14 * * ?
Fire every 5 minutes starting at 2pm and ending at 2:55pm, every day
0 0/5 14,18 * * ?
Fire every 5 minutes starting at 2pm and ending at 2:55pm, AND fire every 5 minutes starting at 6pm and ending at 6:55pm, every day
0 0-5 14 * * ?
Fire every minute starting at 2pm and ending at 2:05pm, every day
0 10,44 14 ? 3 WED
Fire at 2:10pm and at 2:44pm every Wednesday in the month of March.
0 15 10 ? * MON-FRI
Fire at 10:15am every Monday, Tuesday, Wednesday, Thursday and Friday
0 15 10 15 * ?
Fire at 10:15am on the 15th day of every month
0 15 10 L * ?
Fire at 10:15am on the last day of every month
0 15 10 L-2 * ?
Fire at 10:15am on the 2nd-to-last last day of every month
0 15 10 ? * 6L
Fire at 10:15am on the last Friday of every month
0 15 10 ? * 6L
Fire at 10:15am on the last Friday of every month
0 15 10 ? * 6L 2002-2005
Fire at 10:15am on every last friday of every month during the years 2002, 2003, 2004 and 2005
0 15 10 ? * 6#3
Fire at 10:15am on the third Friday of every month
0 0 12 1/5 * ?
Fire at 12pm (noon) every 5 days every month, starting on the first day of the month.
0 11 11 11 11 ?
Fire every November 11th at 11:11am.
Now Let us try some example on Scheduling:
I have used it in one of my projects using jsp-servlet. Here I am giving the code: For using quartz framework, first download the quartz.jar and add it to your lib folder. Now, we have to create two java files. 1) OurCronSchedular.java 2) OurCronJob.java

OurCronSchedular.java: This is the java class where we put all code for setting cron schedular and the time at which the cron trigger will be fired. But our business logic that should be executed when our cron trigger fires, must be written in our job class i.e. OurCronJob.java

package jobScheduling;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.CronTrigger;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.JobDetail;

public class CronSchedular implements ServletContextListener
{
            public static final String QUARTZ_FACTORY_KEY = "org.quartz.impl.StdSchedulerFactory.KEY";
    private ServletContext ctx = null;
    private StdSchedulerFactory factory = null;
   
      //Called when the container is shutting down.
    
    public void contextDestroyed(ServletContextEvent sce)
    {
         try
         {
              factory.getDefaultScheduler().shutdown();
         }
         catch (SchedulerException ex)
         {             
              System.out.println("error in Scheduling.java in contextInitialized() = "+ex);
         }
    }

    //Called when the container is first started.
    
    public void contextInitialized(ServletContextEvent sce)
    {
         ctx = sce.getServletContext();
         try
         {
             factory = new StdSchedulerFactory();             
             
             Scheduler sched=factory.getScheduler();
             JobDetail jd=new JobDetail("job1","group1",OurCronJob.class);
            CronTrigger ct=new CronTrigger("cronTrigger","group2","0 30 14 * * ?");
            sched.scheduleJob(jd,ct);
            sched.start();
             
              ctx.setAttribute(QUARTZ_FACTORY_KEY, factory);
        }
        catch (Exception ex)
        {             
              System.out.println("error in Scheduling.java in contextInitialized() = "+ex);
        }
    }
}


Please click on any advertisement if you like this blog.

OurCronJob.java

package jobScheduling;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import admin.AdminFunctions;
import ScheduleMail.ScheduleMailFunctions;

public class AdvertisementJob implements Job
{
            public void execute(JobExecutionContext context) throws JobExecutionException
            {
                        try
                        {
                                    AdminFunctions.scheduleAdvertisements(7,5);
                        }  
                        catch(Exception ex)                 
                        {
                                    ex.printStackTrace();
                        }
                        try
                        {
                                    ScheduleMailFunctions.birthDayMail(10);
                        }  
                        catch(Exception ex)                 
                        {
                                    ex.printStackTrace();
                        }
                        try
                        {
                                    ScheduleMailFunctions.occasionMail("schedular",null);
                        }  
                        catch(Exception ex)                 
                        {
                                    ex.printStackTrace();
                        }
            }
}
In the above cron job class, I am calling 3 different methods and the noticeable thing is that all the 3 methods are under separate try-catch block. The reason is that if in one method any error occurs, then atleast next method gets called and executed.

In my next post, we will study how to use quarts framework along with Spring Framework.
Please click on any advertisement if you like this blog.

1 comment:

  1. hollow friends help me to develop code "quartz scheduler using jsp with servlet"

    ReplyDelete

Please provide your precious comments and suggestion