Examples of quartz timing function illustrate the configuration method of servlet timer

  • 2020-04-01 02:35:16
  • OfStack

Quartz is a completely open source job scheduling framework written by Java, detailed introduction to the official website http://www.opensymphony.com/quartz/ to view.

The core interfaces and classes of Quartz are:

Job interface: the self-written "timer" implements the void execute(JobExecutionContext arg0) method of this interface. Job also has a class of StatefulJob interfaces, which we need to implement if we need to execute the next Job after the last Job.
Trigger abstract class: the Scheduler class invokes this class when the time is up, and the Trigger class invokes the specified timer.
In the Quertz provides two types of trigger: SimpleTrigger, CronTrigger. The former is used for simple timing functions, such as when to start, when to end, how often to execute, how many times to execute, etc., while the latter provides expressions to describe the timing function, so it is suitable for more complex timing descriptions, such as the last Friday of each month, the Thursday of each week, etc.
JobDetail class: a detailed description of a specific timing program, including Name,Group,JobDataMap, etc.
JobExecutionContext: the run-time context in which the timing program executes, used to get the name of the currently executing Job, configured parameters, and so on.
JobDataMap class: describes a job parameter that can be of any primitive type such as String,float, etc., or a reference to an object.
JobListener, TriggerListener interface: for sweep line status, monitoring the trigger condition and homework in close-up state to perform the corresponding operation.
JobStore class: where to execute the specified program, optionally in memory, in the database.

Simple timing procedure:


public class TestJob implements Job
{
   public TestJob(){}
   public void execute(JobExecutionContext arg0) throws JobExecutionException
   {
      String name = context.getJobDetail().getJobDataMap().getString("name");
      System.out.println("job executing..."+name);   }
}

public class QuartzTest
{
 public static void main(String[] args)
 {
    QuartzTest test = new QuartzTest();
    try
   {
      test.startSchedule();
   }
  catch (Exception e)
  {
     e.printStackTrace();
  }
 }
 public void startSchedule() throws Exception
 {
     Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
     JobDetail jobDetail =
      new JobDetail("testJob", Scheduler.DEFAULT_GROUP, TestJob.class);
      //End time & NBSP;      
     long end = System.currentTimeMillis() + 9000L;
    //Execute 10 times, every 3 seconds, and finish after 9 seconds
     SimpleTrigger trigger = new SimpleTrigger("test",null,new Date(),new Date(end),10,3000L);
      scheduler.scheduleJob(jobDetail, trigger);
     scheduler.start();
 }
}
 

Executing the above class basically implements a simple timing program. However, the problem is that this class can only be applied in the application. To execute in the web environment, you need to add some configuration, such as adding servlets, adding the configuration file quartz.properties or quartz-job.xml(define triiger in the XML file in the configuration way, timing description, etc.).

Used in web applications
 
In the web. Add QuartzInitializerServlet XML, Quartz can be used in web applications, provides a QuartzInitializerServlet and a QuartzInitializerListener, when used to load the web application, initialized to Quartz. I load successfully when I use the servlet and fail when I use the listener. I don't know what happened.

The servlet configuration:


<servlet> 
   <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>config-file</param-name>
    <param-value>quartz.properties</param-value> 
   </init-param>
   <load-on-startup>2</load-on-startup>
 </servlet>
listener Configuration can see the source code, the main above parameter configuration as <context-param>, Add one <listener>.

 As mentioned above quartz.properties, It's self-appointed, Quartz A default configuration file is provided that satisfies the basic j2se Application, if in web In the application, we want to put job,trigger The configuration is written to the file, so we need to write it ourselves and specify that we load our own at initialization time quratz.properties , placed in classes Under. 

#============================================================================
# Configure Main Scheduler Properties  
#============================================================================
org.quartz.scheduler.instanceName = org.quartz.scheduler.instanceId = AUTO
#============================================================================
# Configure ThreadPool  
#============================================================================
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 3
org.quartz.threadPool.threadPriority = 5
#============================================================================
# Configure Plugins 
#============================================================================
org.quartz.plugin.triggHistory.class = org.quartz.plugins.history.LoggingJobHistoryPlugin
org.quartz.plugin.jobInitializer.class = org.quartz.plugins.xml.JobInitializationPlugin
org.quartz.plugin.jobInitializer.fileName = /scheduler/quartz_jobs.xml
org.quartz.plugin.jobInitializer.overWriteExistingJobs = true
org.quartz.plugin.jobInitializer.failOnFileNotFound = true
org.quartz.plugin.jobInitializer.scanInterval = 10

quartz Use plug-ins to load your own xml Configuration file, which we specified above to be loaded at initialization time classes/scheduler/quartz_jobs.xml , is loaded by default classes/quartz_jobs.xml File. 

quartz_jobs.xml File: 
<?xml version='1.0' encoding='utf-8'?>
<quartz>
 <job>
   <job-detail>
    <name>test</name>
    <group>DEFAULT</group>
    <description>testJobhere</description>
    <job-class>TestJob</job-class>
    <job-data-map allows-transient-data="true">
     <entry>
      <key>name</key>
      <value>test</value>
     </entry>
   </job-data-map>
   </job-detail>
   <trigger>
             <cron>
                  <name>testCron</name>
                  <group>DEFAULT</group>
                  <job-name>test</job-name>
                 <job-group>DEFALUT</job-group>
                 <cron-expression>0/3 * * * * ?</cron-expression>
             </cron>
       </trigger>
  </job>
</quartz>


A job is configured and a parameter Name is declared. A CronTrigger is configured to execute every three seconds. If you want to configure SimpleTrigger, you can use < Simple> The label.

The above class corresponding to Job is TestJob, the source code is:


public class TestJob implements Job
{
 public TestJob(){}
 public void execute(JobExecutionContext context) throws JobExecutionException
 {
     String name = context.getJobDetail().getJobDataMap().getString("name");
     System.out.println("job executing..."+name);
 }
}


In quartz_job. XML file you can also specify TriggerListener, JobListener, etc., can use < The trigger - listener> , < The job - listener> Label to specify.

Since there are not many documents on quartz, most of them are based on the source code. In general, the CronTrigger provided by Quartz USES expressions to describe the timing rule, which is very powerful. There are many examples in its source code.

Spring has integrated and packaged quartz, making it easy to use.


Related articles: