2、代码:
SimpleExample:主体程序
HelloJob:一个简单的任务,打印Hello World
HelloJob:
点击(此处)折叠或打开
public class HelloJob implements Job {
private static Logger _log = LoggerFactory.getLogger(HelloJob.class);
public HelloJob() {
}
public void execute(JobExecutionContext context)
throws JobExecutionException {
// Say Hello to the World and display the date/time
_log.info("Hello World! - " + new Date());
}
}
查上面代码,HelloJob只是一个很简单的定时任务,实现了Job接口,同时实现了execute方法,然后方法内打印了当前时间。
SimpleExample:
点击(此处)折叠或打开
package org.quartz.examples.example1;
import static org.quartz.DateBuilder.evenMinuteDate;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
/**
* This Example will demonstrate how to start and shutdown the Quartz scheduler and how to schedule a job to run in
* Quartz.
*
* @author Bill Kratzer
*/
public class SimpleExample {
public void run() throws Exception {
Logger log = LoggerFactory.getLogger(SimpleExample.class);
log.info("------- Initializing ----------------------");
// First we must get a reference to a scheduler
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
log.info("------- Initialization Complete -----------");
// computer a time that is on the next round minute
Date runTime = evenMinuteDate(new Date());
log.info("------- Scheduling Job -------------------");
// define the job and tie it to our HelloJob class
JobDetail job = newJob(HelloJob.class).withIdentity("job1", "group1").build();
// Trigger the job to run on the next round minute
Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(runTime).build();
// Tell quartz to schedule the job using our trigger
sched.scheduleJob(job, trigger);
log.info(job.getKey() + " will run at: " + runTime);
// Start up the scheduler (nothing can actually run until the
// scheduler has been started)
sched.start();
log.info("------- Started Scheduler -----------------");
// wait long enough so that the scheduler as an opportunity to
// run the job!
log.info("------- Waiting 65 seconds... -------------");
try {
// wait 65 seconds to show job
Thread.sleep(65L * 1000L);
// executing...
} catch (Exception e) {
//
}
// shut down the scheduler
log.info("------- Shutting Down ---------------------");
sched.shutdown(true);
log.info("------- Shutdown Complete -----------------");
}
public static void main(String[] args) throws Exception {
SimpleExample example = new SimpleExample();
example.run();
}
}
1)首先创建一个Scheduler,参照quartz详解2,此时还没有打开启动quartz的主线程QuartzSchedulerThread的开关。
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
2)定义JobDetail和Trigger,并添加一个定时任务,在下一个整点执行:
Date runTime = evenMinuteDate(new Date());
// define the job and tie it to our HelloJob class
Date runTime = evenMinuteDate(new Date());JobDetail job = newJob(HelloJob.class).withIdentity("job1", "group1").build();
Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(runTime).build();
sched.scheduleJob(job, trigger);
3)打开开关启动scheduler
// define the job and tie it to our HelloJob class
sched.start();
4)等待65秒后停止Scheduler
sched.shutdown(true);
Example 2 - Simple Triggers
1、实例内容也是Simple Trigger的使用,不一样的是批量的使用。
2、代码:
SimpleTriggerExample:主体程序
SimpleJob:一个简单的任务,打印当前时间
SimpleJob:
点击(此处)折叠或打开
public void execute(JobExecutionContext context)
throws JobExecutionException {
// This job simply prints out its job name and the
// date and time that it is running
JobKey jobKey = context.getJobDetail().getKey();
_log.info("SimpleJob says: " + jobKey + " executing at " + new Date());
}
SimpleTriggerExample:
点击(此处)折叠或打开
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
package org.quartz.examples.example2;
import static org.quartz.DateBuilder.futureDate;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.JobKey.jobKey;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
import org.quartz.DateBuilder;
import org.quartz.DateBuilder.IntervalUnit;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SchedulerMetaData;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
/**
* This Example will demonstrate all of the basics of scheduling capabilities of Quartz using Simple Triggers.
*
* @author Bill Kratzer
*/
public class SimpleTriggerExample {
public void run() throws Exception {
Logger log = LoggerFactory.getLogger(SimpleTriggerExample.class);
log.info("------- Initializing -------------------");
// First we must get a reference to a scheduler
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
log.info("------- Initialization Complete --------");
log.info("------- Scheduling Jobs ----------------");
// jobs can be scheduled before sched.start() has been called
// get a "nice round" time a few seconds in the future...
Date startTime = DateBuilder.nextGivenSecondDate(null, 15);
// job1 will only fire once at date/time "ts"
JobDetail job = newJob(SimpleJob.class).withIdentity("job1", "group1").build();
SimpleTrigger trigger = (SimpleTrigger) newTrigger().withIdentity("trigger1", "group1").startAt(startTime).build();
// schedule it to run!
Date ft = sched.scheduleJob(job, trigger);
log.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every "
+ trigger.getRepeatInterval() / 1000 + " seconds");
// job2 will only fire once at date/time "ts"
job = newJob(SimpleJob.class).withIdentity("job2", "group1").build();
trigger = (SimpleTrigger) newTrigger().withIdentity("trigger2", "group1").startAt(startTime).build();
ft = sched.scheduleJob(job, trigger);
log.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every "
+ trigger.getRepeatInterval() / 1000 + " seconds");
// job3 will run 11 times (run once and repeat 10 more times)
// job3 will repeat every 10 seconds
job = newJob(SimpleJob.class).withIdentity("job3", "group1").build();
trigger = newTrigger().withIdentity("trigger3", "group1").startAt(startTime)
.withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(10)).build();
ft = sched.scheduleJob(job, trigger);
log.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every "
+ trigger.getRepeatInterval() / 1000 + " seconds");
// the same job (job3) will be scheduled by a another trigger
// this time will only repeat twice at a 70 second interval
trigger = newTrigger().withIdentity("trigger3", "group2").startAt(startTime)
.withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(2)).forJob(job).build();
ft = sched.scheduleJob(trigger);
log.info(job.getKey() + " will [also] run at: " + ft + " and repeat: " + trigger.getRepeatCount()
+ " times, every " + trigger.getRepeatInterval() / 1000 + " seconds");
// job4 will run 6 times (run once and repeat 5 more times)
// job4 will repeat every 10 seconds
job = newJob(SimpleJob.class).withIdentity("job4", "group1").build();
trigger = newTrigger().withIdentity("trigger4", "group1").startAt(startTime)
.withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(5)).build();
ft = sched.scheduleJob(job, trigger);
log.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every "
+ trigger.getRepeatInterval() / 1000 + " seconds");
// job5 will run once, five minutes in the future
job = newJob(SimpleJob.class).withIdentity("job5", "group1").build();
trigger = (SimpleTrigger) newTrigger().withIdentity("trigger5", "group1")
.startAt(futureDate(5, IntervalUnit.MINUTE)).build();
ft = sched.scheduleJob(job, trigger);
log.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every "
+ trigger.getRepeatInterval() / 1000 + " seconds");
// job6 will run indefinitely, every 40 seconds
job = newJob(SimpleJob.class).withIdentity("job6", "group1").build();
trigger = newTrigger().withIdentity("trigger6", "group1").startAt(startTime)
.withSchedule(simpleSchedule().withIntervalInSeconds(40).repeatForever()).build();
ft = sched.scheduleJob(job, trigger);
log.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every "
+ trigger.getRepeatInterval() / 1000 + " seconds");
log.info("------- Starting Scheduler ----------------");
// All of the jobs have been added to the scheduler, but none of the jobs
// will run until the scheduler has been started
sched.start();
log.info("------- Started Scheduler -----------------");
// jobs can also be scheduled after start() has been called...
// job7 will repeat 20 times, repeat every five minutes
job = newJob(SimpleJob.class).withIdentity("job7", "group1").build();
trigger = newTrigger().withIdentity("trigger7", "group1").startAt(startTime)
.withSchedule(simpleSchedule().withIntervalInMinutes(5).withRepeatCount(20)).build();
ft = sched.scheduleJob(job, trigger);
log.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every "
+ trigger.getRepeatInterval() / 1000 + " seconds");
// jobs can be fired directly... (rather than waiting for a trigger)
job = newJob(SimpleJob.class).withIdentity("job8", "group1").storeDurably().build();
sched.addJob(job, true);
log.info("'Manually' triggering job8...");
sched.triggerJob(jobKey("job8", "group1"));
log.info("------- Waiting 30 seconds... --------------");
try {
// wait 33 seconds to show jobs
Thread.sleep(30L * 1000L);
// executing...
} catch (Exception e) {
//
}
// jobs can be re-scheduled...
// job 7 will run immediately and repeat 10 times for every second
log.info("------- Rescheduling... --------------------");
trigger = newTrigger().withIdentity("trigger7", "group1").startAt(startTime)
.withSchedule(simpleSchedule().withIntervalInMinutes(5).withRepeatCount(20)).build();
ft = sched.rescheduleJob(trigger.getKey(), trigger);
log.info("job7 rescheduled to run at: " + ft);
log.info("------- Waiting five minutes... ------------");
try {
// wait five minutes to show jobs
Thread.sleep(300L * 1000L);
// executing...
} catch (Exception e) {
//
}
log.info("------- Shutting Down ---------------------");
sched.shutdown(true);
log.info("------- Shutdown Complete -----------------");
// display some stats about the schedule that just ran
SchedulerMetaData metaData = sched.getMetaData();
log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");
}
public static void main(String[] args) throws Exception {
SimpleTriggerExample example = new SimpleTriggerExample();
example.run();
}
}
job3每10秒执行1次,重复10次,一共执行11次。
点击(此处)折叠或打开
// job3 will run 11 times (run once and repeat 10 more times)
// job3 will repeat every 10 seconds
job = newJob(SimpleJob.class).withIdentity("job3", "group1").build();
trigger = newTrigger().withIdentity("trigger3", "group1").startAt(startTime)
.withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(10)).build();
同样是job3,新增一个trigger来触发它。
因为在版本2.2.1中,是可以支持多个trigger来对应触发同一个JOB的。
点击(此处)折叠或打开
trigger = newTrigger().withIdentity("trigger3", "group2").startAt(startTime)
.withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(2)).forJob(job).build();
job5也可以设置5分钟后执行:
点击(此处)折叠或打开
// job5 will run once, five minutes in the future
job = newJob(SimpleJob.class).withIdentity("job5", "group1").build();
trigger = (SimpleTrigger) newTrigger().withIdentity("trigger5", "group1")
.startAt(futureDate(5, IntervalUnit.MINUTE)).build();
job6设置每40秒执行,一直执行:
点击(此处)折叠或打开
job = newJob(SimpleJob.class).withIdentity("job6", "group1").build();
trigger = newTrigger().withIdentity("trigger6", "group1").startAt(startTime)
.withSchedule(simpleSchedule().withIntervalInSeconds(40).repeatForever()).build();
job7是可以在scheduler启动后再创建,加入到scheduler中。
job8表示,不需要创建trigger,可以直接触发任务。
example3:Cron Triggerjob1是每20秒执行一次:
点击(此处)折叠或打开
JobDetail job = newJob(SimpleJob.class)
.withIdentity("job1", "group1")
.build();
CronTrigger trigger = newTrigger()
.withIdentity("trigger1", "group1")
.withSchedule(cronSchedule("0/20 * * * * ?"))
.build();
sched.scheduleJob(job, trigger);
Jo2是每2分钟执行一次,在15秒这个点执行。如1分15秒,3分15秒,5分15秒。
点击(此处)折叠或打开
JobDetail job = newJob(SimpleJob.class)
.withIdentity("job1", "group1")
.build();
CronTrigger trigger = newTrigger()
.withIdentity("trigger1", "group1")
.withSchedule(cronSchedule("0/20 * * * * ?"))
.build();
sched.scheduleJob(job, trigger);
JOB3是每2分种的整点执行一次,在上午8点到下午17点之间。
点击(此处)折叠或打开
// job 3 will run every other minute but only between 8am and 5pm
job = newJob(SimpleJob.class).withIdentity("job3", "group1").build();
trigger = newTrigger().withIdentity("trigger3", "group1").withSchedule(cronSchedule("0 0/2 8-17 * * ?")).build();
ft = sched.scheduleJob(job, trigger);
log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: "
+ trigger.getCronExpression());
JOB5在每个月1号和15号的上午10点执行:
点击(此处)折叠或打开
// job 5 will run at 10am on the 1st and 15th days of the month
job = newJob(SimpleJob.class).withIdentity("job5", "group1").build();
trigger = newTrigger().withIdentity("trigger5", "group1").withSchedule(cronSchedule("0 0 10am 1,15 * ?")).build();
ft = sched.scheduleJob(job, trigger);
log.info(job.getKey() + " has been scheduled to run at: " + ft + " and repeat based on expression: "
+ trigger.getCronExpression());
JOB6在每周一到周五执行,每30秒执行一次。
"0,30 * * ? * MON-FRI"
JOB7在每个周六和周日执行,每30秒执行一次。
"0,30 * * ? * MON-FRI"
Example 4 -Job Parameters and Job State
可以为job设置参数和状态。