Nice book and well written book by nice author.
1) If your Java applications depend on tasks that must be performed at specific times or if your systems have recurring maintenance jobs that could be automated, then you need Quartz: the first full-featured, open source job scheduling framework.
2) Using Quartz Within a Web Application
You might want to integrate Quartz within a Web application for several reasons. A few of the more obvious ones are listed here:
To schedule and launch jobs using a GUI interface
To improve job management and monitoring
To make it easier for multiple users to schedule jobs
To schedule jobs from within your own Web applications
The primary use of Quartz within a Web app is, of course, to allow easier scheduling and maintenance of jobs through a GUI interface. Other secondary reasons include better management of running and scheduled jobs, as well as quicker notification when things go wrong. In general, the same reasons that you would want to put a GUI around any software application can be generalized for applications using Quartz: to make it easier to use the application.
3) The Quartz framework includes a Java servlet called org.quartz.ee.servlet. QuartzInitializerServlet, which extends a standard HttpServlet. You can use this servlet in your Web application, and it will create a StdSchedulerFactory instance and make it available to the rest of your application.
4) The SchedulerFactory and Scheduler Can Be Easily Accessed in this below way.
public class StartSchedulerAction extends Action {
public ActionForward execute(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
// Retrieve the ServletContext
ServletContext ctx =
request.getSession().getServletContext();
// Retrieve the factory from the ServletContext
StdSchedulerFactory factory =
(StdSchedulerFactory)
ctx.getAttribute(
QuartzFactoryServlet.QUARTZ_FACTORY_KEY);
// Retrieve the scheduler from the factory
Scheduler scheduler = factory.getScheduler();
// Start the scheduler
scheduler.start();
// Forward to success page
return mapping.findForward(WebConstants.SUCCESS);
}
}
5) Using a ServletContextListener
It's worth mentioning that you can configure and integrate Quartz within a Web application in another way. Starting with version 2.3 of the Servlet API, you can create listeners that get callbacks from the servlet container at certain times during the life cycle of the container. One of the listener interfaces is called javax.servlet.ServletContextListener and contains two methods:
public void contextInitialized(ServletContextEvent sce);
public void contextDestroyed(ServletContextEvent sce );
6) Uses for Job Schedulers in the Enterprise
The term enterprise is used so oftenand so carelesslytoday that it's hard to know which definition is being referred to. We have one meaning in mind when we use it in this book: the software systems and processes that are part of an organization. These systems might be legacy mainframes, a client/server architecture, or J2EE applicationsit doesn't matter. Realworld examples of where job schedulers can be used are plentiful. The following scenarios, although obviously not exhaustive, present some common uses in applications today.
Scenario #1: Sending E-Mails, Reminders, and Alerts
Many web sites (both commercial and otherwise) allow users to register an account that includes a username and password. For security reasons, it's a good idea to expire the user's passwords regularlysay, every 90 days. You might create a job that runs every night at midnight and sends an e-mail to a list of users when their passwords will expire in three days. This is great use of a job scheduler.
Besides expiring passwords, Web sites can send other alerts and reminders(not to mention spam). A job scheduler can be used for those in a similar way.
Scenario #2: Performing File-Transfer Operations
Many businesses need to integrate information with their vendors and clients. One method of performing this integration is to exchange data files. Businesses can use real-time methods such as SOAP, but many don't need to operate in real time and instead choose asynchronous methods such as File Transfer Protocol (ftp) to drop and pick up files.
Picture a worker's compensation company that receives files every morning containing patient/accident information. This company could hire someone to manually check the ftp site every morning for the file. Alternatively, someone could write a job that executes every morning to scan the ftp site and insert the files into the patient database. With a scheduled job, the employee no longer has to perform the manual checks and can do something more valuable for the company.
Scenario #3: Creating Sales Reports
Companies are driven on profit and loss, and it's important to have the latest revenue and margin data for executives and the finance team to analyze. Pulling the data for sales reports can be very slow and resource intensive because it usually involves searching thousands of records and joining many database tables. A better approach involves running a job every night after the billing and invoicing is updated to create temporary tables or views that then can be used to run reports against. Creating temp tables or views makes the reports more dynamic, and users won't get frustrated while waiting for a report to generate. Some reporting packages, such as Crystal Reports XI, include a job scheduler.
7) Quartz was created by James House, who envisioned the first conceptual pieces of the framework in 1998. These included the concept of a queue of jobs and a pool of threads to process the jobs, although probably in an unrecognizable form by most of today's Quartz users.
8) Regardless of the type of Scheduler you use, you should never create an instance of the Scheduler directly. Instead, you should use one of the factory methods to ensure that all facets of the Scheduler are instantiated and initialized properly. (The factory design pattern is referred to as a factory pattern because it is responsible for "manufacturing" an object. In this case, it manufactures a Scheduler instance) The Quartz framework provides the org.quartz.SchedulerFactory interface for this purpose. The role of the SchedulerFactory is to produce Scheduler instances. When created, the instances are stored in a repository (org.quartz.impl.SchedulerRepository) that provides lookup facilities within a class loader. To use the Scheduler instances, the client must retrieve them from the factory (and subsequent repository) by using a separate method call. In other words, creating a Scheduler instance through the factory and getting the instance of that Scheduler takes two method calls. Some convenience methods encapsulate those two calls, as you'll see shortly.
9) Threads are extremely important to Quartz because Quartz is designed to support multiple Jobs running simultaneously. To perform this feat, Quartz relies heavily on the thread support built into the Java language and augments it with a few of its own classes and interfaces.
When a Quartz Scheduler is first created through one of the factory methods, the factory configures several important resources that the Scheduler will need throughout its lifetime. A few of those important resources have to do with threads.
When a Quartz application is first launched, the main thread starts the Scheduler. The QuartzScheduler is created and creates an instance of the org.quartz.core.QuartzSchedulerThread class. The QuartzSchedulerThread contains the processing loop for determining when the next job should be triggered. As the name implies, the QuartzSchedulerThread is a Java thread. It runs as a nondaemon thread with a normal priority.
Quartz doesn't process your jobs on the main thread. If it did, it would severely reduce the scalability of the application. Instead, Quartz delegates the thread-management responsibilities to a separate component. For the generic Quartz setup, which most users employ, the SimpleThreadPool class handles thread management. The SimpleThreadPool creates a number of WorkerThread instances that are responsible for processing a job on a separate thread. The WorkerThread is an inner class defined within the SimpleThreadPool class and is essentially a thread. The number of WorkerThreads that are created and the priority for these threads are specified by the configuration settings in the quartz.properties file or are passed into the factory.
The JobRunShell run() Method
Although WorkerThreads are indeed Java threads, the JobRunShell class implements Runnable as well. That means that it can act as a thread and contains a run() method. As discussed earlier in the chapter, the purpose of the JobRunShell is to call the execute() method on a job. It does this and also notifies the job and trigger listeners, and it finishes by updating trigger information about the execution.
10) You can't increment beyond the fields range. For example, you can't specify 30/20 in the second field and expect the scheduler to fire correctly.
11) The / Character
The slash (/) character is used to schedule increments. We just used the comma to increment every 15 minutes, but we could have also written it like 0/15.
Example expression:
0/15 0/30 * * * ?
Meaning: Fire the trigger every 15 seconds on the hour and half-hour.
You can't increment beyond the fields range. For example, you can't specify 30/20 in the second field and expect the scheduler to fire correctly.
12) The # Character
The # character can be used only in the dayofweek field. It's used to specify the nth XXX day of the month. For example, if you specified the value 6#3 in the dayofweek field, it would mean the third Friday of the month (6 = Friday and #3 means the third one in the month). Another example of 2#1 means the first Monday of the month (2 = Monday and #1 means the first one of the month). Note that if you specify #5 and there is no 5 of the given day of the week in the month, no firing will occur that month.
13) As with the JobListener, the org.quartz.TriggerListener interface contains a set of methods that the Scheduler calls. Unlike the JobListener, however, the triggerListener interface contains life cycle methods for trigger instances.
public interface TriggerListener {
public String getName();
public void triggerFired(Trigger trigger,
JobExecutionContext context);
public boolean vetoJobExecution(Trigger trigger,
JobExecutionContext context);
public void triggerMisfired(Trigger trigger);
public void triggerComplete(Trigger trigger,
JobExecutionContext context,
int triggerInstructionCode);
}
Below program shows a very simple TRiggerListener implementation.
public class SimpleTriggerListener implements TriggerListener {
Log logger = LogFactory.getLog(SimpleTriggerListener.class);
private String name;
public SimpleTriggerListener(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void triggerFired(Trigger trigger,
JobExecutionContext context) {
String triggerName = trigger.getName();
logger.info(triggerName + " was fired");
}
public boolean vetoJobExecution(Trigger trigger,
JobExecutionContext context) {
String triggerName = trigger.getName();
logger.info(triggerName + " was not vetoed");
return false;
}
public void triggerMisfired(Trigger trigger) {
String triggerName = trigger.getName();
logger.info(triggerName + " misfired");
}
public void triggerComplete(Trigger trigger,
JobExecutionContext context,
int triggerInstructionCode) {
String triggerName = trigger.getName();
logger.info(triggerName + " is complete");
}
}
14) A workflow is a set of interdependent tasks that occur in a specific sequence.
About the Author
Chuck Cavaness is the Chief Technology Officer at Cypress Care, Inc. and a software technologist with more than 10 years of technical management, software engineering, and development experience. Chuck has spent time in the travel, health-care, banking, and B2B/B2C sectors, and has spent the past several years building large enterprise J2EE systems for the financial and health-care industries.
Chuck is a published author of five books on popular technologies, including books on Java J2EE and many open source technologies such as Apache Struts. He has also written for JavaWorld, O'Reilly, OnJava, and InformIt.com and has taught courses on programming and software development at Georgia Institute of Technology.
7 comments:
Hey nice blog - could you tell me if I could use Quartz to schedule jobs where the date/time are specified in the database?
Raghu,
yes you can infact do it.
Let me know if you need any help.
Thanks
Prashant
There some problems with Quartz that I'm having right now.
- It doen't schedule jobs fast even if RAMDataStore is used.
- There is only one thread QuartzSchedulerThread to fire the jobs on time. This may cause misfire if more jobs are scheduled at the same time.
- If you have hundred thousand jobs to schedule, try to write your own JobStore and trigger. They needs optimisations. For example, RAMJobStore.triggers field is a bottleneck for some situations because it is ArrayList.
- Quartz code is really very dirty. It needs deep refactoring.
Good days...
Hasan Unal
Thats a wonderful blog. I would like to know more about the job failures. What happens when we have set of jobs running and we need to restart them from where they stopped. The state management and job recovery process.
Thats a wonderful blog. I would like to know more about the job failures. What happens when we have set of jobs running and we need to restart them from where they stopped. The state management and job recovery process.
Hi ,
actually i m going to use Cron Scheudler for my Web App,where user is allowed to craete there schedule.
What my plan is to store all schedules in XML file under 'UserName' node.As schdule time matches with XML it will raed corrsponding Java class.M not using DB .i will read XML every time to run job.as i will create this Schduelr class as autoexe as it shold run as system start. Wanna know m i right to implement this .
Other one problem is I don't know how to give GUI for this Schedule any help regarding GUI.
Pls lemme know if u can help regarding these points , as i have to start development for this
Thanks
vikram
virendravikram06@gmail.com
Hello,
Just a heads up on the QuartzDesk project which you may find a very valuable tool when working with Quartz based applications.
QartzDesk is an advanced Quartz scheduler manager and monitoring GUI / tool with many unique and powerful features such as:
* Support for Quartz 1.x and 2.x schedulers.
* Persistent job execution history.
* Job execution log message capturing.
* Notifications (email, all popular IM protocols, web-service).
* Interactive execution statistics and charts.
* REST API for job / trigger / scheduler monitoring.
* QuartzAnywhere web-service to manage / monitor Quartz schedulers from applications.
* and more
The product is aimed at all Java developers using the Quartz scheduler in their applications, as well as system administrators / operations personnel looking after these applications.
Lite (completely free) edition available. 30-day trials for non-free editions available.
Jan Moravec
QuartzDesk Founder
Post a Comment