Quartz programmatically invoking an instance of __

Source: Internet
Author: User

What is job schedule system?
The job schedule system is the one that is responsible for executing or notifying an application component at a predefined time. For example, send an email informing the customer of the latest business situation at 9:30 every morning.

Java.util.Timer and Java.util.TimerTask
The timer and TimerTask are the classes provided by the two JDK that can complete the job schedule, but this is not called a system. The timer and TimerTask are very simple and do not directly support the scheduling of persistent tasks, thread pools, and similar calendars (calendar-like), and developers are going to do a lot of scaling up in completing some advanced features.

A brief introduction to Quartz
Quartz is opensymphony organization specialized job scheduling field another open source weapon, can go to Http://www.opensymphony.com/quartz view detailed information. Quartz is a lightweight component that developers only need to load a separate jar package to take advantage of Quartz's powerful scheduling capabilities. Of course, if you have the features of the database persistence task for quartz, quartz can also take advantage of this, so that you can remember the plan you originally scheduled after the machine restarts.

The interface that we touch most in quartz makes the Scheduler interface, which provides scheduled functions such as Schedule/unschedule plan, Start/pause/stop Scheduler.

Quartz provides some common listener (joblistener,triggerlistener,schedulerlistener) for full monitoring of scheduling and execution.

start our quartz tour. HelloWorld Example:

Presumably everyone would like to see an example of HelloWorld, then start with Hellowworld.

Import java.util.Date;
 import Org.quartz.Job;
 import Org.quartz.JobDetail;
 import Org.quartz.JobExecutionContext;
 import org.quartz.JobExecutionException;
 import Org.quartz.Scheduler;
 import org.quartz.SchedulerFactory;
 import Org.quartz.Trigger;
 import org.quartz.impl.StdSchedulerFactory;
 /**
  * @author snowway
  * @version $Id $
  */
 public class Sayhelloworldjob Implements job{
    /*
      * (non-javadoc)
       *
      * @see Org.quartz.job#execute ( Org.quartz.JobExecutionContext)
      */
     public void Execute (Jobexecutioncontext context) throws jobexecutionexception{
          System.out.println ("Hello world!");
    }

public static void Main (string[] args) throws exception{
Schedulerfactory factory = new Stdschedulerfactory ();
Scheduler Scheduler = Factory.getscheduler ();

Jobdetail jobdetail = new Jobdetail ("Sayhelloworldjob",
Scheduler.default_group,
Sayhelloworldjob.class);

         Trigger Trigger = new Simpletrigger ("Sayhelloworldjobtrigger",
                 Scheduler.default_group,
                  new Date (),
                  NULL,
                  0,
                  0L);
         scheduler.schedulejob (jobdetail, Trigger);
         Scheduler.start ();
    }
 }

For the sake of simplicity, I wrote the Main method in Sayhelloworldjob and executed sayhelloworldjob to see the console print Hello world. Review Hello World Example:

What the job is.
An interface job is an interface that needs to be implemented for every task that needs to be performed on a business, and that interface has only one method:

Package Org.quartz;

Public interface Job {

public void execute (jobexecutioncontext context)
Throws Jobexecutionexception;
}

The Execute method is the method of quartz callback when time arrives, we make sayhelloworldjob implement the job interface to provide printing function

What is Jobdetail.
Jobdetail describes a task-specific information, such as name, group name, and so on.
Jobdetail jobdetail = new Jobdetail ("Sayhelloworldjob",
Scheduler.default_group,
Sayhelloworldjob.class);
In the construction method above, the first is the name of the task, the second is the group name, and the third is the callback class that the task needs to execute.

What is trigger.
Trigger as the name implies is a trigger, quartz has a good idea is to separate the task and task execution conditions. Trigger is the class that controls task execution conditions, and trigger notifies the relevant job to execute when trigger thinks the execution condition is satisfied. The benefits of separation are:
1. You can associate multiple trigger for a job, and any one of these conditions can trigger job execution, which can complete some combination of advanced trigger conditions
2. When the trigger fails (for example, a condition that can never be met), you do not have to declare a new job, instead you can associate a new trigger with the job so that the job can continue to execute.

In the present quartz implementation, there are two kinds of trigger,simpletrigger and Crontrigger,simpletrigger used to accomplish some tasks such as fixed-time execution, such as: 1 minutes from now and so on, and Crontrigger ( Yes, the same as the UNIX cron process) is used to perform calendar-like tasks, such as: Every Friday 3:00, the last day of the month, and so on.

Trigger Trigger = new Simpletrigger ("Sayhelloworldjobtrigger",
Scheduler.default_group,
New Date (),
Null
0,
0L);
In this construction method, the first is the name of the trigger, the second is the trigger group name, the third is the task start time, the fourth is the end time, and the fifth is the duplicate
Number of times (using the simpletrigger.repeat_indefinitely constant for Infinity), and the last is the repeating period (in milliseconds), this creates
A task that was performed immediately and only once.

Scheduler.schedulejob (Jobdetail, Trigger);
This is a statement that associates the job with the trigger, so that when trigger thinks it should be triggered, the Job.execute method is called (actually scheduler called).

Scheduler.start ();
Don't forget to add the above statement, this statement informs Quartz to make the scheduled plan take effect.

About the parameters of the Execute method jobexecutioncontext
Jobexecutioncontext, like many of the context-terminated class functions, provides a run-time contextual environment that Jobexecutioncontext
Scheduler,jobdetail,trigger is a reference to many objects, so that when you need them within the Execute method it is necessary to provide the convenience of these objects at all times.

Name and group of Jobdetail and Trigger
Scheduler instances correspond to many instances of job and trigger, and for the sake of convenience, Quartz uses both the name and group features, as you would like to
The same group cannot have two jobdetail,trigger of the same name.
The same scheduler cannot have two identical group Jobdetail,trigger.
The fully qualified name of Jobdetail and trigger is: Group + name more in-depth thinking ...


HelloWorld's example is not enough to illustrate some of the questions that some might ask: what if some extra data is needed in the Execute method. such as execute.
Would like to send a message, but I need to know the sender of the message, the recipient and other information?

There are two types of solutions:
1.JobDataMap class:
Each jobdetail is associated with a Jobdatamap instance, Jobdatamap is a subclass of Java.util.Map, essentially providing data in the form of Key-value, and provides a number of convenient methods (primarily support for Java basic data types, such as put (String key,int value)). When the developer creates the Jobdetail, the additional information can be placed in the Jobdatamap, then the Execute method can find the desired value according to the key.
Jobdetail job = new Jobdetail ....
Job.getjobdatamap (). Put ("from", "snowway@vip.sina.com");
...

In Execute
String from = Jobexecutioncontext.getjobdetail (). Getjobdatamap (). getString ("from");
....

However, when you use database storage Jobdetail (using RAM by default), there is a fatal weakness here, You cannot put an object that does not implement java.io.Serializable into jobdatamap because quartz will use the BLOB field to save (or close through the configuration file) the objects in the serialized jobdatamap. For example, if you need a Java.sql.Connection interface instance in the Execute method, which is also common, you cannot normally put connection into jobdatamap, even if you only want to use it in execute. (Note: The reader may temporarily consider the above paragraph to be correct, but can change this behavior by instructing quartz, which is a high-level topic)

2. If you need a java.sql.Connection to perform certain operations in execute, you can put Connection into quartz schedulercontext, execute is also accessible, and quartz will not persist Schedul Anything in the Ercontext.

Scheduler.getcontext (). Put ("Java.sql.Connection", Connection);

In Execute
Connection con = (Connection) Jobexecutioncontext.getscheduler (). GetContext (). Get ("java.sql.Connection");

Not to be continued ...

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.