Home > Articles

This chapter is from the book

Scheduling a Quartz Job Declaratively

As discussed earlier, we would like to handle configuring our software declaratively rather than programmatically as much as possible. Looking back at Listing 3.6, if we needed to change the time or frequency at which the jobs started, we would have to modify the source and recompile. This is fine for small example applications, but with a system that is large and complex, this quickly becomes a problem. So if there's a way to schedule Quartz jobs declaratively and your requirements allow for it, you should choose that approach every time.

Before we can discuss how to schedule your jobs declaratively, we need to talk about the quartz.properties file. This properties file enables you to configure the runtime environment of Quartz and, more important, tell Quartz to get the job and trigger information from an external resource, such as an XML file.

Configuring the quartz.properties File

The quartz.properties file defines the runtime behavior of the Quartz application and contains many properties that can be set to control how Quartz behaves. Only the basics are covered within this chapter; we save the more advanced settings for later. We also do not go into detail about the valid values for each setting at this point.

Let's look at a bare-bones quartz.properties file and discuss some of the settings. Listing 3.7 shows a stripped-down version of the quartz.properties file.

Example 3.7. Basic Quartz Properties File

#===============================================================
#Configure Main Scheduler Properties
#===============================================================
org.quartz.scheduler.instanceName = QuartzScheduler
org.quartz.scheduler.instanceId = AUTO

#===============================================================
#Configure ThreadPool
#===============================================================
org.quartz.threadPool.threadCount =  5
org.quartz.threadPool.threadPriority = 5
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool

#===============================================================
#Configure JobStore
#===============================================================
org.quartz.jobStore.class = org.quartz.simpl.RAMJobStore

#===============================================================
#Configure Plugins
#===============================================================
org.quartz.plugin.jobInitializer.class =
org.quartz.plugins.xml.JobInitializationPlugin

org.quartz.plugin.jobInitializer.overWriteExistingJobs = true
org.quartz.plugin.jobInitializer.failOnFileNotFound = true
org.quartz.plugin.jobInitializer.validating=false

In the quartz.properties file in Listing 3.7, the properties are logically separated into four sections. The properties don't have to be grouped or listed in any order. The lines with the # are comments.

Scheduler Properties

The first section contains two lines and sets the instanceName and instanceId for the Scheduler. The value for the property org.quartz.scheduler.instanceName can be any string that you like. It's used to distinguish a particular scheduler instance when multiple schedulers are being used. Multiple schedulers are normally used within a clustered environment. (Quartz clustering is discussed in Chapter 11, "Clustering Quartz.") For now, a string such as this one is fine:

org.quartz.scheduler.instanceName = QuartzScheduler

In fact, that is the default when none is provided in the properties file.

The second Scheduler property shown in Listing 3.7 is org.quartz.scheduler.instanceId. As with the instanceName property, the instanceId property can be any string value you want. The value should be unique across all Scheduler instances, especially within a cluster. You may use the value AUTO if you want the value to be generated for you. The generated value will be NON_CLUSTERED if this is running in a nonclustered Quartz environment. If you're using Quartz in a clustered environment, the value will be the hostname of the machine plus the current date and time. For most situations, setting the value to AUTO is fine.

Threadpool Properties

The next section sets the necessary values for the threads that run in the background and do the heavy lifting in Quartz. The threadCount property controls how many worker threads are created and available to process jobs. In principal, the more jobs that you have to process, the more worker threads you'll need. The number for the threadCount must be at least 1. Quartz imposes no maximum on the number of worker threads, but setting this value to greater than 100 on most machines becomes quite unwieldy, especially if your jobs have long-running logic in them. There is no default, so you must specify a value for this property.

The threadPriority property sets the priority that the worker threads run with. Threads with higher priorities are typically given preference over threads with a lower priority. The minimum value for the threadPriority is the constant java.lang.Thread.MAX_PRIORITY, which equates to 10. The minimum value is java.lang.Thread.MIN_PRIORITY, which equals 1. The typical value for this property is Thread.NORM_PRIORITY, which is 5. For most situations, you'll want to set this to the value of 5, which is the default if the property isn't specified.

The final threadpool setting is for the property org.quartz.threadPool.class. The value for this class should be a fully qualified name of the class that implements the org.quartz.spi.ThreadPool interface. The threadpool that ships with Quartz is org.quartz.simpl.SimpleThreadPool, and it should meet the needs of most users. This threadpool has simple behavior and is well tested. It provides a fixed-size pool of threads that survive the lifetime of the Scheduler. You can create your own threadpool class, if you want. For example, you might need to do this if you want a threadpool that grows and shrinks with demand. There is no default specified, so you must provide a value for this property.

Jobstore Settings

The properties within the JobStore section describe how job and trigger information is stored during the lifetime of the Scheduler instance. We haven't yet talked about the JobStore and its purpose; we save that for later because it's not necessary for the current example. For now, all you need to know is that we are storing Scheduler information in memory instead of a relational database.

Storing Scheduler information in memory is fast and the easiest to configure. When the Scheduler process is halted, however, all job and trigger state is lost. Job storage in memory is accomplished by setting the org.quartz.jobStore.class property to org.quartz.simpl.RAMJobStore, as we've done in Listing 3.7. If we don't want to lose our Scheduler state when the JVM is halted, we could use a relational database to store that information. This requires a different JobStore implementation that we discuss later. Chapters 5, "Cron Triggers and More," and 6, "JobStores and Persistence," cover the various types of JobStores and when you should use them.

Plug-In Settings

The final section in the simple quartz.properties file is the one that specifies any Quartz plug-ins that you want to configure. A plug-in is used by many other open source frameworks, such as Struts from Apache (see http://struts.apache.org).

The idea is to declaratively extend the framework by adding classes that implement the org.quartz.spi.SchedulerPlugin interface. The SchedulerPlugin interface has three methods that are called by the Scheduler.

To declaratively configure the Scheduler information for our example, we will be using a plug-in called org.quartz.plugins.xml.JobInitializationPlugin that comes with Quartz.

By default, this plug-in searches for a file called quartz_jobs.xml in the classpath and loads job and trigger information from the XML file.

The next section discusses the quartz_jobs.xml file, which we informally refer to as the job definition file.

Using the quartz_jobs.xml File

Listing 3.8 shows the job-definition XML file for the Scan Directory example. It configures job and trigger information using a declarative approach exactly like the example from Listing 3.5.

Example 3.8. The quartz_ jobs.xml file for the ScanDirectory Job

<?xml version='1.0' encoding='utf-8'?>

<quartz>

  <job>
    <job-detail>
     <name>ScanDirectory</name>
     <group>DEFAULT</group>
     <description>
          A job that scans a directory for files
     </description>
     <job-class>
            org.cavaness.quartzbook.chapter3.ScanDirectoryJob
     </job-class>
     <volatility>false</volatility>
     <durability>false</durability>
     <recover>false</recover>
     <job-data-map allows-transient-data="true">
         <entry>
         <key>SCAN_DIR</key>
         <value>c:\quartz-book\input</value>
       </entry>
     </job-data-map>
    </job-detail>

    <trigger>
     <simple>
       <name>scanTrigger</name>
       <group>DEFAULT</group>
       <job-name>ScanDirectory</job-name>
       <job-group>DEFAULT</job-group>
       <start-time>2005-06-10 6:10:00 PM</start-time>
       <!-- repeat indefinitely every 10 seconds -->
       <repeat-count>-1</repeat-count>
       <repeat-interval>10000</repeat-interval>
     </simple>
    </trigger>

  </job>
</quartz>

The <job> element represents a job that you want to register with the Scheduler, just as we did earlier in the chapter with the scheduleJob() method. You can see the <job-detail> and <trigger> elements, which we programmatically passed into the schedulerJob() method in Listings 3.5. This is essentially what is happening here, but in a declarative fashion. You can also see in Listing 3.8 that we set the SCAN_DIR property into the JobDataMap, as we also did in the Listing 3.5 example.

The <trigger> element is also very intuitive: It simply sets up a SimpleTrigger with the same properties as before. So Listing 3.8 is just a different (arguably, better) way of doing what we did in Listing 3.5. You obviously can support multiple jobs as well. We did this in Listing 3.6 programmatically, and we can also support it declaratively. Listing 3.9 shows the comparable version of Listing 3.6.

Example 3.9. You Can Specify Multiple Jobs in the quartz_jobs.xml File

<?xml version='1.0' encoding='utf-8'?>

<quartz>
  <job>
    <job-detail>
     <name>ScanDirectory1</name>
     <group>DEFAULT</group>
     <description>
           A job that scans a directory for files
     </description>
     <job-class>
           org.cavaness.quartzbook.chapter3.ScanDirectoryJob
     </job-class>
     <volatility>false</volatility>
     <durability>false</durability>
     <recover>false</recover>

     <job-data-map allows-transient-data="true">
     <entry>
       <key>SCAN_DIR</key>
         <value>c:\quartz-book\input1</value>
     </entry>
    </job-data-map>
  </job-detail>

  <trigger>
    <simple>
     <name>scanTrigger1</name>
     <group>DEFAULT</group>
     <job-name>ScanDirectory1</job-name>
     <job-group>DEFAULT</job-group>
     <start-time>2005-07-19 8:31:00 PM</start-time>
     <!-- repeat indefinitely every 10 seconds -->
     <repeat-count>-1</repeat-count>
     <repeat-interval>10000</repeat-interval>
    </simple>
  </trigger>
</job>

<job>
  <job-detail>
    <name>ScanDirectory2</name>
    <group>DEFAULT</group>
    <description>
          A job that scans a directory for files
    </description>
    <job-class>
          org.cavaness.quartzbook.chapter3.ScanDirectoryJob
    </job-class>
    <volatility>false</volatility>
    <durability>false</durability>
    <recover>false</recover>

    <job-data-map allows-transient-data="true">
      <entry>
       <key>SCAN_DIR</key>
       <value>c:\quartz-book\input2</value>
     </entry>
    </job-data-map>
  </job-detail>

  <trigger>
    <simple>
     <name>scanTrigger2</name>
     <group>DEFAULT</group>
     <job-name>ScanDirectory2</job-name>
     <job-group>DEFAULT</job-group>
     <start-time>2005-06-10 6:10:00 PM</start-time>
     <!-- repeat indefinitely every 15 seconds -->
     <repeat-count>-1</repeat-count>
     <repeat-interval>15000</repeat-interval>
    </simple>
  </trigger>
 </job>
</quartz>

Modifying the quartz.properties File for the Plug-In

Earlier in this chapter, you were told that the JobInitializationPlugin looks for the file quartz_jobs.xml to get the declarative job information. If you want to change that file, you need to modify the quartz.properties file and tell the plug-in which file to load. For example, if you wanted Quartz to load job information from an XML file called my_quartz_jobs.xml , you would have to give the plug-in that filename. Listing 3.10 shows how this can be accomplished; we are only repeating the plug-in section here.

Example 3.10. Modifying quartz.properties for JobInitializationPlugin

org.quartz.plugin.jobInitializer.class =
org.quartz.plugins.xml.JobInitializationPlugin

org.quartz.plugin.jobInitializer.fileName = my_quartz_jobs.xml

org.quartz.plugin.jobInitializer.overWriteExistingJobs = true
org.quartz.plugin.jobInitializer.validating = false
org.quartz.plugin.jobInitializer.overWriteExistingJobs = false
org.quartz.plugin.jobInitializer.failOnFileNotFound = true

In Listing 3.10, we add the property org.quartz.plugin.jobInitializer.fileName and set the value to the name of our file. It must be available to the classloader, which means somewhere on the classpath.

When Quartz starts up and reads the quartz.properties file, it initializes the plug-in. It passes all of these properties to the plug-in, and the plug-in gets notified to look for a different file.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020