April 01, 2013

Job scheduling in web application with Quartz..


Quartz with Simple Servlet

What is Quartz?
Quartz is a Java job-scheduling system capable of initialization , scheduling and executing jobs in a very flexible manner.

Web.xml

<servlet>
<servlet-name>InitializeServlet</servlet-name>
<servlet-class>com.testing.cron.InitializeServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

How to create a Custom Job

Job's are built by implementing the org.quartz.Job interface as follows:

public void execute(JobExecutionContext context) throws JobExecutionException;

The interface is very simple and concise, with just one method to be implemented. The Scheduler will invoke the execute method when the trigger associated with the job fires. The JobExecutionContext object passed as an argument has all the context and environment data for the job, such as the JobDataMap.

The JobDataMap is very similar to a Java map but provides strongly typed put and get methods. This JobDataMap is set in the JobDetail file before scheduling the job and can be retrieved later during the execution of the job via the JobExecutionContext's getJobDetail().getJobDataMap() method.


Example to create custom job : MyJob.java

package com.testing.cron;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class MyJob implements Job {

    public void execute(JobExecutionContext context)throws JobExecutionException
    {
                System.out.println("******Executing Cron Job");
    }
}


How to Schedule a Job?

SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sche = sf.getScheduler();
sche.start();


Above lines will create a SchedulerFactory, an object that creates Schedulers, and then proceed to create and start a new Scheduler.

This Scheduler will fire the trigger and subsequently the jobs associated with the trigger. After creating the Scheduler, we must create a JobDetail object that contains information about the job to be executed, the job group to which it belongs, and other administrative data.

JobDetail jDetail = new JobDetail("Newsletter", "NJob", MyJob.class);

This JobDetail tells the Scheduler to instantiate a MyJob object when appropriate, has a 'NJob' JobGroup, and has a Job name of "Newsletter".

After defining the JobDetail, we must create and define the Trigger, that is, when the Job will be executed and how many times, etc.

Trigger trigger = TriggerUtils.makeHourlyTrigger(); // fire every hour
trigger.setStartTime(TriggerUtils.getEvenHourDate(new Date())); // start on the next even hour
trigger.setName("myTrigger");


The TriggerUtils is a helper object used to simplify the trigger code. With the help of the TriggerUtils, we will create a trigger that will fire every hour. This trigger will start firing the next even hour after the trigger is registered with the Scheduler. The last line of code puts a name to the trigger for housekeeping purposes.


Or

CronTrigger crTrigger = new CronTrigger("cronTrigger", "NJob", "0/2 * * * * ?"); // [Check Cron Trigger below]

Finally, the last line of code associates the trigger with the job and puts them under the control of the Scheduler.

sche.scheduleJob(jDetail, crTrigger);

When the next even hour arrives after this line of code is executed, the Scheduler will fire the trigger and it will execute the job by reading the JobDetail and instantiating the MyJob.class. This requires that the class implementing the job interface must have a no-arguments constructor.


CronTrigger

It is based on the concept of the UNIX Cron utility. It lets you specify complex schedules, like every Wednesday at 5.00 AM, or every twenty minutes, or every 5 seconds on Monday. Like the SimpleTrigger, the CronTrigger has a start time property and an optional end time.

A CronExpression is made of seven parts, each representing a time component:

Each number represents a time part:
  • 1 represents seconds
  • 2 represents minutes
  • 3 represents hours
  • 4 represents the day-of-month
  • 5 represents month
  • 6 represents the day-of-week
  • 7 represents year (optional field)


Name
Required
Allowed Values
Allowed Special Characters
Seconds
Y
0-59
, - * /
Minutes
Y
0-59
, - * /
Hours
Y
0-23
, - * /
Day of month
Y
Jan-31
, - * ? / L W C
Month
Y
0-11 or JAN-DEC
, - * /
Day of week
Y
1-7 or SUN-SAT
, - * ? / L C #
Year
N
empty or 1970-2099
, - * /


The '*' character is used to specify all values. For example, "*" in the minute field means "every minute".

The '?' character is allowed for the day-of-month and day-of-week fields. It is used to specify 'no specific value'. This is useful when you need to specify something in one of the two fileds, but not the other. See the examples below for clarification.

The '-' character is used to specify ranges For example "10-12" in the hour field means "the hours 10, 11 and 12".

The ',' character is used to specify additional values. For example "MON,WED,FRI" in the day-of-week field means "the days Monday, Wednesday, and Friday".

The '/' character is used to specify increments. For example "0/15" in the seconds field means "the seconds 0, 15, 30, and 45". And "5/15" in the seconds field means "the seconds 5, 20, 35, and 50". Specifying '*' before the '/' is equivalent to specifying 0 is the value to start with. Essentially, for each field in the expression, there is a set of numbers that can be turned on or off. For seconds and minutes, the numbers range from 0 to 59. For hours 0 to 23, for days of the month 0 to 31, and for months 1 to 12. The "/" character simply helps you turn on every "nth" value in the given set. Thus "7/6" in the month field only turns on month "7", it does NOT mean every 6th month, please note that subtlety.

The 'L' character is allowed for the day-of-month and day-of-week fields. This character is short-hand for "last", but it has different meaning in each of the two fields. For example, the value "L" in the day-of-month field means "the last day of the month" - day 31 for January, day 28 for February on non-leap years. If used in the day-of-week field by itself, it simply means "7" or "SAT". But if used in the day-of-week field after another value, it means "the last xxx day of the month" - for example "6L" means "the last friday of the month". When using the 'L' option, it is important not to specify lists, or ranges of values, as you'll get confusing results.

The 'W' character is allowed for the day-of-month field. This character is used to specify the weekday (Monday-Friday) nearest the given day. As an example, if you were to specify "15W" as the value for the day-of-month field, the meaning is: "the nearest weekday to the 15th of the month". So if the 15th is a Saturday, the trigger will fire on Friday the 14th. If the 15th is a Sunday, the trigger will fire on Monday the 16th. If the 15th is a Tuesday, then it will fire on Tuesday the 15th. However if you specify "1W" as the value for day-of-month, and the 1st is a Saturday, the trigger will fire on Monday the 3rd, as it will not 'jump' over the boundary of a month's days. The 'W' character can only be specified when the day-of-month is a single day, not a range or list of days.

The 'L' and 'W' characters can also be combined for the day-of-month expression to yield 'LW', which translates to "last weekday of the month".

The '#' character is allowed for the day-of-week field. This character is used to specify "the nth" XXX day of the month. For example, the value of "6#3" in the day-of-week field means the third Friday of the month (day 6 = Friday and "#3" = the 3rd one in the month). Other examples: "2#1" = the first Monday of the month and "4#5" = the fifth Wednesday of the month. Note that if you specify "#5" and there is not 5 of the given day-of-week in the month, then no firing will occur that month.

The 'C' character is allowed for the day-of-month and day-of-week fields. This character is short-hand for "calendar". This means values are calculated against the associated calendar, if any. If no calendar is associated, then it is equivalent to having an all-inclusive calendar. A value of "5C" in the day-of-month field means "the first day included by the calendar on or after the 5th". A value of "1C" in the day-of-week field means "the first day included by the calendar on or after sunday".

The legal characters and the names of months and days of the week are not case sensitive.

Here are a couple of examples of cron expression:

Expression
Means
0 0 12 * * ?
Fire at 12:00 PM (noon) every day
0 15 10 ? * *
Fire at 10:15 AM every day
0 15 10 * * ?
Fire at 10:15 AM every day
0 15 10 * * ? *
Fire at 10:15 AM every day
0 15 10 * * ? 2005
Fire at 10:15 AM every day during the year 2005
0 * 14 * * ?
Fire every minute starting at 2:00 PM and ending at 2:59 PM, every day
0 0/5 14 * * ?
Fire every 5 minutes starting at 2:00 PM and ending at 2:55 PM, every day
0 0/5 14,18 * * ?
Fire every 5 minutes starting at 2:00 PM and ending at 2:55 PM, AND fire every 5 minutes starting at 6:00 PM and ending at 6:55 PM, every day
0 0-5 14 * * ?
Fire every minute starting at 2:00 PM and ending at 2:05 PM, every day
0 10,44 14 ? 3 WED
Fire at 2:10 PM and at 2:44 PM every Wednesday in the month of March
0 15 10 ? * MON-FRI
Fire at 10:15 AM every Monday, Tuesday, Wednesday, Thursday and Friday
0 15 10 15 * ?
Fire at 10:15 AM on the 15th day of every month
0 15 10 L * ?
Fire at 10:15 AM on the last day of every month
0 15 10 ? * 6L
Fire at 10:15 AM on the last Friday of every month
0 15 10 ? * 6L
Fire at 10:15 AM on the last Friday of every month
0 15 10 ? * 6L 2002-2005
Fire at 10:15 AM on every last friday of every month during the years 2002, 2003, 2004, and 2005
0 15 10 ? * 6#3
Fire at 10:15 AM on the third Friday of every month
0 0 12 1/5 * ?
Fire at 12 PM (noon) every 5 days every month, starting on the first day of the month
0 11 11 11 11 ?
Fire every November 11 at 11:11 AM
0 0/5 * * * ?
Cron Expression to fire the trigger every five minutes:
0 0 * * * ?
Cron Expression to fire the trigger every hour
0 0 0/2 * * ?
Cron Expression to fire the trigger every two Hours
0 0 0/4 * * ?
Cron expression to fire the trigger every Four Hours
20 0/10 * * * ?(e.g. 10:00:20, 10:10:20, 10:20:20)
Cron Expression to fire the trigger every 10 Minutes 20 Seconds
0 0/30 1-7 5, 20 * ? (e.g. 2010-07-20 1:00:00, 2010-07-20 1:30:00m 2010-07-20 2:00:00)
Every half an hour between 1 AM to 7 AM on 20th of Every Month
0 25 1-5 ? * MON,WED
Cron Expression to fire the trigger on the 25th Minute from 1 AM to 5 PM on every Monday and Wednesday
0 0 12 * * ?
Cron Expression to fire the trigger at Noon every day
0 0 12 * * 2010
Cron Expression to fire the trigger at Noon every day only in 2010
0 0/10 9, 17 * * ?
Cron Expression to fire the trigger Every 10 minutes between 9 AM to 5 PM (until 5:50) Every Day
0 30 14 ? * 7L
Cron Expression to fire the trigger at 2:30 PM on the last Saturday of every month.
0 10 7 ? * MON-FRI
Cron Expression to fire the trigger at 7:10 AM every Monday, Tuesday, Wednesday, Thursday and Friday
0 10,40 14 ? 7 SUN
Cron Expression to fire the trigger at 2:10 PM and at 2:40 PM every Sunday in the month of July.


e.g:
CronTrigger crTrigger = new CronTrigger("cronTrigger", "NJob", "CronTrigger");
CronTrigger crTrigger = new CronTrigger("cronTrigger", "NJob", "0/2 * * * * ?");

CronScheduler.java

package com.testing.cron;

import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

public class CronScheduler
{
    public CronScheduler() throws Exception
    {
        SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler sche = sf.getScheduler();
        sche.start();
        JobDetail jDetail = new JobDetail("Newsletter", "NJob", MyJob.class);
        CronTrigger crTrigger = new CronTrigger("cronTrigger", "NJob", "0/2 * * * * ?");
        sche.scheduleJob(jDetail, crTrigger);
    }
}

InitializeServlet.java

package com.testing.cron;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
public class InitializeServlet extends HttpServlet
{
 public void init() throws ServletException
 {
    try
    {
        CronScheduler cronScheduler = new CronScheduler();
    }
    catch (Exception ex) {
      ex.printStackTrace();
    }
  }
}

Jars

quartz-1.6.6.jar
quartz-all-1.6.6.jar
quartz-jboss-1.6.6.jar
quartz-oracle-1.6.6.jar
quartz-weblogic-1.6.6.jar


 -K Himaanshu Shukla...



Copyright © 2013 - ScrutinyByKHimaanshu

4 comments:

Anonymous said...

Thanks a ton for writing such a nice blog

Anonymous said...

Gr8 job with nice examples. Thanks a ton

Anonymous said...

Hi Dude I am getting classnotfound error. please let me know how to resolve this issue.

Error log:

java.lang.ClassNotFoundException: CronJobTest.com.testing.cron.InitializeServlet
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1386)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1232)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1068)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:966)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3996)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4266)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:927)
at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:890)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)

Thanks in advance

Vaibhav Yadav

Thanh Hùng Nguyễn said...

Bài post của tác giả rất hay, cám ơn bạn đã chia sẻ.
Xem tại website : Thạch anh vụn

Post a Comment

RSSChomp Blog Directory