Example 1: Job
Implementationorg.quartz.job
Interface to make the Java class executable. Listing 1 provides an example of a quartz job. This class uses a very simple output statement to overwriteexecute(JobExecutionContext context)
Method. This method can contain any code we want to execute (all code examples are based on quartz 1.5.2, which is the stable release version when writing this article ).
Listing 1. simplequartzjob. Java
package com.ibm.developerworks.quartz;
import java.util.Date; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException;
public class SimpleQuartzJob implements Job {
public SimpleQuartzJob() { }
public void execute(JobExecutionContext context) throws JobExecutionException { System.out.println("In SimpleQuartzJob - executing its JOB at " + new Date() + " by " + context.getTrigger().getName()); } }
|
Note that the execute method accepts oneJobExecutionContext
Object as a parameter. This object provides the runtime context of the job instance. In particular, it provides access to the scheduler and trigger, the two work together to start the job and the jobJobDetail
Object execution. Quartz places the job status inJobDetail
Object andJobDetail
The constructor starts a job instance and separates the execution of the job from the status around the job.JobDetail
Object Storage job listeners, groups, data ing, descriptions, and other job attributes.
Example 2: simple trigger
A trigger can schedule a task. Quartz provides several different triggers with different levels of complexity. In Listing 2SimpleTrigger
Demonstrate the trigger basics:
Listing 2. simpletriggerrunner. Java
public void task() throws SchedulerException { // Initiate a Schedule Factory SchedulerFactory schedulerFactory = new StdSchedulerFactory(); // Retrieve a scheduler from schedule factory Scheduler scheduler = schedulerFactory.getScheduler();
// current time long ctime = System.currentTimeMillis();
// Initiate JobDetail with job name, job group, and executable job class JobDetail jobDetail = new JobDetail("jobDetail-s1", "jobDetailGroup-s1", SimpleQuartzJob.class); // Initiate SimpleTrigger with its name and group name SimpleTrigger simpleTrigger = new SimpleTrigger("simpleTrigger", "triggerGroup-s1"); // set its start up time simpleTrigger.setStartTime(new Date(ctime)); // set the interval, how often the job should run (10 seconds here) simpleTrigger.setRepeatInterval(10000); // set the number of execution of this job, set to 10 times. // It will run 10 time and exhaust. simpleTrigger.setRepeatCount(100); // set the ending time of this job. // We set it for 60 seconds from its startup time here // Even if we set its repeat count to 10, // this will stop its process after 6 repeats as it gets it endtime by then. //simpleTrigger.setEndTime(new Date(ctime + 60000L)); // set priority of trigger. If not set, the default is 5 //simpleTrigger.setPriority(10); // schedule a job with JobDetail and Trigger scheduler.scheduleJob(jobDetail, simpleTrigger);
// start the scheduler scheduler.start(); }
|
Listing 2 instantiatesSchedulerFactory
To obtain the scheduler. As discussed earlierJobDetail
Object, its constructor must acceptJob
As a parameter. As the name suggests,SimpleTrigger
The instance is quite primitive. After creating an object, set several basic attributes to schedule the task immediately and repeat the task every 10 seconds until the job is executed for 100 times.
There are many other ways to manipulateSimpleTrigger
. In addition to specifying the number of repetitions and repetition interval, you can also specify the maximum execution time or priority of a job in a specific calendar time (discussed later ). The maximum execution time can overwrite the specified number of repetitions to ensure that the running of the job does not exceed the maximum time.
Example 3: cron trigger
CronTrigger
Support RatioSimpleTrigger
More specific scheduling is not very complex. Based on cron expressions,CronTrigger
Supports repetition intervals similar to calendars, rather than a single interval.SimpleTrigger
It is a major improvement.
Cron expressions include the following seven fields:
- Seconds
- Minute
- Hours
- Date in month
- Month
- Week date
- Year (optional)
Special characters
The cron trigger uses a series of special characters, as shown below:
- The backslash (/) character indicates the increment value. For example, in the second field, "5/15" indicates that the value starts from 5th seconds, every 15 seconds.
- Question mark (?) The characters and letters are only available in the Date Field of the month and the date field of the week. The question mark indicates that this field does not contain specific values. Therefore, if you specify a date in the month, you can insert "?" In the Date Field of the week, Indicates that the date value of the week is irrelevant. The letter L isLast
. In the Date Field of the month, the task is executed on the last day of the month. In the week Date Field, if "L" exists separately, it is equal to "7". Otherwise, it represents the last instance of the week date in the current month. Therefore, "0l" indicates that it will be executed on the last Sunday of the month.
- The letter (w) in the date field within the month is executed on the workday closest to the specified value. Place "1 W" in the Date Field of the month, which means that the execution is arranged within the first business day of the month.
- The pound sign (#) specifies a specific workday instance for a given month. Put "Mon #2" in the Date Field of the week, indicating that the task is scheduled for the second Monday of the month.
- The asterisk (*) character is a wildcard character, indicating that this field can accept any possible value.
All these definitions may seem a little scary, but after a few minutes of practice, the cron expression will look very simple.
Listing 3 showsCronTrigger
. Note:SchedulerFactory
,Scheduler
AndJobDetail
AndSimpleTrigger
The instantiation In the example is the same. In this example, the trigger is modified. The cron expression specified here ("0/5 ****?") Schedule task execution every 5 seconds.
Listing 3. crontriggerrunner. Java
public void task() throws SchedulerException
{
// Initiate a Schedule Factory
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
// Retrieve a scheduler from schedule factory
Scheduler scheduler = schedulerFactory.getScheduler();
// current time
long ctime = System.currentTimeMillis();
// Initiate JobDetail with job name, job group, and executable job class
JobDetail jobDetail =
new JobDetail("jobDetail2", "jobDetailGroup2", SimpleQuartzJob.class);
// Initiate CronTrigger with its name and group name
CronTrigger cronTrigger = new CronTrigger("cronTrigger", "triggerGroup2");
try {
// setup CronExpression
CronExpression cexp = new CronExpression("0/5 * * * * ?");
// Assign the CronExpression to CronTrigger
cronTrigger.setCronExpression(cexp);
} catch (Exception e) {
e.printStackTrace();
}
// schedule a job with JobDetail and Trigger
scheduler.scheduleJob(jobDetail, cronTrigger);
// start the scheduler
scheduler.start();
}
This article from: http://hi.baidu.com/maomaoyusp/blog/item/77b1318762afb02cc75cc32c.html