项目地址:
https://github.com/yuleiqq/quartz_example/tree/master/quartz_study
此示例旨在演示如何将运行时参数传递给quartz作业,以及如何维护作业中的状态。
程序将执行以下操作:
启动Quartz调度器
调度两个作业,每个作业将执行总共10秒一次
调度程序将向第一个作业实例传递一个运行时作业参数“Green”
调度程序将把运行时作业参数“Red”传递给第二个作业实例
程序将等待60秒,以便两个作业有足够的时间运行
关闭调度程序
本例中的代码由以下类组成:
JobStateExample : 主运行程序
ColorJob:一个简单的作业,打印一个最喜欢的颜色(作为运行时参数传入)并显示它的执行计数。
针对ColorJob,需要加如下两个注解,否则持久存储不会生效
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class ColorJob implements Job {
话不多人,直接贴代码,看运行效果吧
ColorJob.java
package com.example05;
import java.util.Date;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.quartz.PersistJobDataAfterExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* This is just a simple job that receives parameters and
* maintains state
* </p>
*
* @author Bill Kratzer
*/
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class ColorJob implements Job {
private static Logger _log = LoggerFactory.getLogger(ColorJob.class);
// parameter names specific to this job
public static final String FAVORITE_COLOR = "favorite color";
public static final String EXECUTION_COUNT = "count";
// Since Quartz will re-instantiate a class every time it
// gets executed, members non-static member variables can
// not be used to maintain state!
private int _counter = 1;
/**
* <p>
* Empty constructor for job initialization
* </p>
* <p>
* Quartz requires a public empty constructor so that the
* scheduler can instantiate the class whenever it needs.
* </p>
*/
public ColorJob() {
}
/**
* <p>
* Called by the <code>{@link org.quartz.Scheduler}</code> when a
* <code>{@link org.quartz.Trigger}</code> fires that is associated with
* the <code>Job</code>.
* </p>
*
* @throws JobExecutionException
* if there is an exception while executing the job.
*/
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();
// Grab and print passed parameters
JobDataMap data = context.getJobDetail().getJobDataMap();
String favoriteColor = data.getString(FAVORITE_COLOR);
int count = data.getInt(EXECUTION_COUNT);
_log.info("ColorJob: " + jobKey + " executing at " + new Date() + "\n" +
" favorite color is " + favoriteColor + "\n" +
" execution count (from job map) is " + count + "\n" +
" execution count (from job member variable) is " + _counter);
// increment the count and store it back into the
// job map so that job state can be properly maintained
count++;
data.put(EXECUTION_COUNT, count);
// Increment the local member variable
// This serves no real purpose since job state can not
// be maintained via member variables!
_counter++;
}
}
JobStateExample.java
package com.example05;
import static org.quartz.DateBuilder.nextGivenSecondDate;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
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 how job parameters can be passed into jobs and how state can be maintained
*
* @author Bill Kratzer
*/
public class JobStateExample {
public void run() throws Exception {
Logger log = LoggerFactory.getLogger(JobStateExample.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 ----------------");
// get a "nice round" time a few seconds in the future....
Date startTime = nextGivenSecondDate(null, 10);
// job1 will only run 5 times (at start time, plus 4 repeats), every 10 seconds
JobDetail job1 = newJob(ColorJob.class).withIdentity("job1", "group1").build();
SimpleTrigger trigger1 = newTrigger().withIdentity("trigger1", "group1").startAt(startTime)
.withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4)).build();
// pass initialization parameters into the job
job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Green");
job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);
// schedule the job to run
Date scheduleTime1 = sched.scheduleJob(job1, trigger1);
log.info(job1.getKey() + " will run at: " + scheduleTime1 + " and repeat: " + trigger1.getRepeatCount()
+ " times, every " + trigger1.getRepeatInterval() / 1000 + " seconds");
// job2 will also run 5 times, every 10 seconds
JobDetail job2 = newJob(ColorJob.class).withIdentity("job2", "group1").build();
SimpleTrigger trigger2 = newTrigger().withIdentity("trigger2", "group1").startAt(startTime)
.withSchedule(simpleSchedule().withIntervalInSeconds(10).withRepeatCount(4)).build();
// pass initialization parameters into the job
// this job has a different favorite color!
job2.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Red");
job2.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);
// schedule the job to run
Date scheduleTime2 = sched.scheduleJob(job2, trigger2);
log.info(job2.getKey().toString() + " will run at: " + scheduleTime2 + " and repeat: " + trigger2.getRepeatCount()
+ " times, every " + trigger2.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 -----------------");
log.info("------- Waiting 60 seconds... -------------");
try {
// wait five minutes to show jobs
Thread.sleep(60L * 1000L);
// executing...
} catch (Exception e) {
//
}
log.info("------- Shutting Down ---------------------");
sched.shutdown(true);
log.info("------- Shutdown Complete -----------------");
SchedulerMetaData metaData = sched.getMetaData();
log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");
}
public static void main(String[] args) throws Exception {
JobStateExample example = new JobStateExample();
example.run();
}
}
执行后,结果如下:
[INFO] 24 三月 06:12:08.584 下午 main [com.example05.JobStateExample]
------- Initializing -------------------
[INFO] 24 三月 06:12:08.662 下午 main [org.quartz.impl.StdSchedulerFactory]
Using default implementation for ThreadExecutor
[INFO] 24 三月 06:12:08.691 下午 main [org.quartz.core.SchedulerSignalerImpl]
Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
[INFO] 24 三月 06:12:08.691 下午 main [org.quartz.core.QuartzScheduler]
Quartz Scheduler v.2.3.0 created.
[INFO] 24 三月 06:12:08.693 下午 main [org.quartz.simpl.RAMJobStore]
RAMJobStore initialized.
[INFO] 24 三月 06:12:08.694 下午 main [org.quartz.core.QuartzScheduler]
Scheduler meta-data: Quartz Scheduler (v2.3.0) 'MyScheduler' with instanceId 'NON_CLUSTERED'
Scheduler class: 'org.quartz.core.QuartzScheduler' - running locally.
NOT STARTED.
Currently in standby mode.
Number of jobs executed: 0
Using thread pool 'org.quartz.simpl.SimpleThreadPool' - with 20 threads.
Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.
[INFO] 24 三月 06:12:08.695 下午 main [org.quartz.impl.StdSchedulerFactory]
Quartz scheduler 'MyScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
[INFO] 24 三月 06:12:08.695 下午 main [org.quartz.impl.StdSchedulerFactory]
Quartz scheduler version: 2.3.0
[INFO] 24 三月 06:12:08.695 下午 main [com.example05.JobStateExample]
------- Initialization Complete --------
[INFO] 24 三月 06:12:08.695 下午 main [com.example05.JobStateExample]
------- Scheduling Jobs ----------------
[INFO] 24 三月 06:12:08.716 下午 main [com.example05.JobStateExample]
group1.job1 will run at: Tue Mar 24 18:12:10 CST 2020 and repeat: 4 times, every 10 seconds
[INFO] 24 三月 06:12:08.716 下午 main [com.example05.JobStateExample]
group1.job2 will run at: Tue Mar 24 18:12:10 CST 2020 and repeat: 4 times, every 10 seconds
[INFO] 24 三月 06:12:08.716 下午 main [com.example05.JobStateExample]
------- Starting Scheduler ----------------
[INFO] 24 三月 06:12:08.717 下午 main [org.quartz.core.QuartzScheduler]
Scheduler MyScheduler_$_NON_CLUSTERED started.
[INFO] 24 三月 06:12:08.717 下午 main [com.example05.JobStateExample]
------- Started Scheduler -----------------
[INFO] 24 三月 06:12:08.717 下午 main [com.example05.JobStateExample]
------- Waiting 60 seconds... -------------
[INFO] 24 三月 06:12:10.018 下午 MyScheduler_Worker-1 [com.example05.ColorJob]
ColorJob: group1.job1 executing at Tue Mar 24 18:12:10 CST 2020
favorite color is Green
execution count (from job map) is 1
execution count (from job member variable) is 1
[INFO] 24 三月 06:12:10.020 下午 MyScheduler_Worker-2 [com.example05.ColorJob]
ColorJob: group1.job2 executing at Tue Mar 24 18:12:10 CST 2020
favorite color is Red
execution count (from job map) is 1
execution count (from job member variable) is 1
[INFO] 24 三月 06:12:20.010 下午 MyScheduler_Worker-3 [com.example05.ColorJob]
ColorJob: group1.job1 executing at Tue Mar 24 18:12:20 CST 2020
favorite color is Green
execution count (from job map) is 2
execution count (from job member variable) is 1
[INFO] 24 三月 06:12:20.010 下午 MyScheduler_Worker-4 [com.example05.ColorJob]
ColorJob: group1.job2 executing at Tue Mar 24 18:12:20 CST 2020
favorite color is Red
execution count (from job map) is 2
execution count (from job member variable) is 1
[INFO] 24 三月 06:12:30.000 下午 MyScheduler_Worker-5 [com.example05.ColorJob]
ColorJob: group1.job1 executing at Tue Mar 24 18:12:30 CST 2020
favorite color is Green
execution count (from job map) is 3
execution count (from job member variable) is 1
[INFO] 24 三月 06:12:30.000 下午 MyScheduler_Worker-6 [com.example05.ColorJob]
ColorJob: group1.job2 executing at Tue Mar 24 18:12:30 CST 2020
favorite color is Red
execution count (from job map) is 3
execution count (from job member variable) is 1
[INFO] 24 三月 06:12:40.001 下午 MyScheduler_Worker-7 [com.example05.ColorJob]
ColorJob: group1.job1 executing at Tue Mar 24 18:12:40 CST 2020
favorite color is Green
execution count (from job map) is 4
execution count (from job member variable) is 1
[INFO] 24 三月 06:12:40.002 下午 MyScheduler_Worker-8 [com.example05.ColorJob]
ColorJob: group1.job2 executing at Tue Mar 24 18:12:40 CST 2020
favorite color is Red
execution count (from job map) is 4
execution count (from job member variable) is 1
[INFO] 24 三月 06:12:50.001 下午 MyScheduler_Worker-9 [com.example05.ColorJob]
ColorJob: group1.job1 executing at Tue Mar 24 18:12:50 CST 2020
favorite color is Green
execution count (from job map) is 5
execution count (from job member variable) is 1
[INFO] 24 三月 06:12:50.002 下午 MyScheduler_Worker-10 [com.example05.ColorJob]
ColorJob: group1.job2 executing at Tue Mar 24 18:12:50 CST 2020
favorite color is Red
execution count (from job map) is 5
execution count (from job member variable) is 1
[INFO] 24 三月 06:13:08.718 下午 main [com.example05.JobStateExample]
------- Shutting Down ---------------------
[INFO] 24 三月 06:13:08.718 下午 main [org.quartz.core.QuartzScheduler]
Scheduler MyScheduler_$_NON_CLUSTERED shutting down.
[INFO] 24 三月 06:13:08.718 下午 main [org.quartz.core.QuartzScheduler]
Scheduler MyScheduler_$_NON_CLUSTERED paused.
[INFO] 24 三月 06:13:09.104 下午 main [org.quartz.core.QuartzScheduler]
Scheduler MyScheduler_$_NON_CLUSTERED shutdown complete.
[INFO] 24 三月 06:13:09.104 下午 main [com.example05.JobStateExample]
------- Shutdown Complete -----------------
[INFO] 24 三月 06:13:09.104 下午 main [com.example05.JobStateExample]
Executed 10 jobs.
由结果可以看出,存储在JobDataMap 中的count 状态每次递增加1,成员变量的 _counter 没有变化,因为job 每次执行都会重新创建一个Job类.