Quartz implementation of timing function examples (servlet timer configuration method) _java

Source: Internet
Author: User
Tags function examples

Quartz is a completely Java-written open source job scheduling framework, the specific introduction can be viewed on the official website of http://www.opensymphony.com/quartz/.

Quartz's several core interfaces and classes are:

Job interface: The "timer program" You write itself implements the void execute (Jobexecutioncontext arg0) method for this interface, and the job has a class of statefuljob interfaces that are stateful, if we need to finish the last job. You need to implement this interface if you want to execute the next job based on its execution results.
Trigger abstract class: The scheduling Class (Scheduler) calls this class at time, and then the specified timer is invoked by the trigger class.
Two types of triggers are provided in Quertz: Simpletrigger,crontrigger. The former is used to implement a relatively simple timing function, such as the beginning, the time, how many times to execute, the total number of executions, the latter provides the use of expressions to describe the timing function, so it is suitable for more complex timing description, such as the last Friday month, the weekly Thursday, etc.
Jobdetail class: Detailed description of a specific timing procedure, including Name,group,jobdatamap.
Jobexecutioncontext class: The Run-time context in which the timer program executes to get the name of the currently executing job, the parameters of the configuration, and so on.
Jobdatamap class: A parameter that describes a job, which can be any base type such as String,float, or a reference to an object.
Joblistener,triggerlistener interface: Used to listen for trigger status and job sweep status, perform actions in close-up state.
Jobstore class: Where to perform the scheduler, optionally there is in memory, in the database.

Simple Timing Program:

Copy Code code as follows:

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
Long end = System.currenttimemillis () + 9000L;
Executes 10 times, executes every 3 seconds, and ends in 9 seconds
Simpletrigger trigger = new Simpletrigger ("Test", Null,new date (), new date (end), 10,3000l);
Scheduler.schedulejob (Jobdetail, Trigger);
Scheduler.start ();
}
}

The implementation of the above class basically implements a simple timer program. The problem is that this class can only be applied to application, and some configuration needs to be added to the web environment, such as adding a servlet, adding a profile quartz.properties or quartz-job.xml ( Define Triiger, timed description, etc. in the XML file in a configuration way.

Use in Web applications

Add Quartzinitializerservlet,quartz in Web.xml to be able to be used in Web applications, providing a quartzinitializerservlet and a quartzinitializerlistener for loading web When applied, initializes the quartz. I was successful when I was using the servlet, I didn't succeed when I was using listener, I don't know what's going on?

Servlet configuration:

Copy Code code as follows:

<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 look at the source code, the main parameters of the above configuration for <context-param&gt, and then add a <listener>

The above mentioned quartz.properties, which is specified by itself, Quartz provides a default configuration file to meet the basic J2SE application, if in the Web application, we want to write Job,trigger configuration to the file, we need to write, and specifies that our own quratz.properties be loaded at initialization time, with the position placed under classes.

#============================================================================
# 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 to use a plug-in to load its own XML configuration file, we specify that the Classes/scheduler/quartz_jobs.xml is loaded at initialization time, and the default is to load the 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>
&LT;CRON-EXPRESSION&GT;0/3 * * * *?</cron-expression>
</cron>
</trigger>
</job>
</quartz>


A job is configured and a parameter name is declared, and a Crontrigger is configured to execute once every three seconds. If you want to configure Simpletrigger, you can use the <simple> tab.

The above and job corresponding class is testjob, the source code is:

Copy Code code as follows:

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);
}
}


Triggerlistener,joblistener can also be specified in the Quartz_job.xml file, which can be specified using the <trigger-listener>,<job-listener> tag.

Since Quartz is currently not a lot of documents, most of them are looking at the source. Overall look at the quartz provided by the Crontrigger use expressions to describe the timing of the rule is still very powerful, in its source code has many examples.

Spring has integrated the quartz and encapsulated it, and it's easy to use.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.