=======================================================================
以下属于个人观点,难免有错误,如发现错误请留言告之,我会订正的。
=======================================================================
这篇讲解怎么设置参数传递给执行的任务,我们需要用到jobDataMap()这个方法。
JobDataMap能够支持任何序列化的对象,当job执行时,这些对象能够在job实例中可用。JobDataMap实现了Java Map接口,它有一些附加的方法,这些方法用来储存和跟踪简单类型的数据。如下代码可以很快地给job增加JobDataMap:
- jobDetail.getJobDataMap().put("jobSays", "Hello World!");
- jobDetail.getJobDataMap().put("myFloatValue", 3.141f);
- jobDetail.getJobDataMap().put("myStateData", new ArrayList());
在job执行时,我们可以在job里通过如下代码得到JobDataMap:
- public class DumbJob implements Job {
- public DumbJob() {
- }
- public void execute(JobExecutionContext context)
- throws JobExecutionException
- {
- String instName = context.getJobDetail().getName();
- String instGroup = context.getJobDetail().getGroup();
- JobDataMap dataMap = context.getJobDetail().getJobDataMap();
- String jobSays = dataMap.getString("jobSays");
- float myFloatValue = dataMap.getFloat("myFloatValue");
- ArrayList state = (ArrayList)dataMap.get("myStateData");
- state.add(new Date());
- System.err.println("Instance " + instName + " of DumbJob says: " + jobSays);
- }
- }
看官方的例子里,我们在run()方法里可以看到:
- JobDetail job = newJob(ColorJob.class)
- .withIdentity("job1", "group1")
- .build();
- job.getJobDataMap().put(key, value);
只要put(key,value)即可传递参数。
我们在实现了job接口的类中
- JobDataMap data = context.getJobDetail().getJobDataMap();
- String favoriteColor = data.getString(key);
- int count = data.getInt(key);
看官方提供的例子example4:
JobStateExample.java
- package main.java.org.quartz.examples.example4;
- import static org.quartz.JobBuilder.newJob;
- import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
- import static org.quartz.TriggerBuilder.newTrigger;
- import static org.quartz.DateBuilder.*;
- import java.util.Date;
- 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;
- public class JobStateExample {
- public void run() throws Exception {
- Logger log = LoggerFactory.getLogger(JobStateExample.class);
- log.info("------- Initializing -------------------");
- SchedulerFactory sf = new StdSchedulerFactory();
- Scheduler sched = sf.getScheduler();
- log.info("------- Initialization Complete --------");
- log.info("------- Scheduling Jobs ----------------");
- Date startTime = nextGivenSecondDate(null, 10);
- JobDetail job1 = newJob(ColorJob.class)
- .withIdentity("job1", "group1")
- .build();
- SimpleTrigger trigger1 = newTrigger()
- .withIdentity("trigger1", "group1")
- .startAt(startTime)
- .withSchedule(simpleSchedule()
- .withIntervalInSeconds(10)
- .withRepeatCount(4))
- .build();
- //设置参数,调用ColorJob中的默认变量
- job1.getJobDataMap().put(ColorJob.FAVORITE_COLOR, "Green");
- job1.getJobDataMap().put(ColorJob.EXECUTION_COUNT, 1);
- Date scheduleTime1 = sched.scheduleJob(job1, trigger1);
- log.info(job1.getKey() +
- " will run at: " + scheduleTime1 +
- " and repeat: " + trigger1.getRepeatCount() +
- " times, every " + trigger1.getRepeatInterval() / 1000 + " seconds");
- log.info("------- Starting Scheduler ----------------");
- sched.start();
- log.info("------- Started Scheduler -----------------");
- log.info("------- Waiting 60 seconds... -------------");
- try {
- Thread.sleep(60L * 1000L);
- } 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();
- }
- }
ColorJob.java
- package main.java.org.quartz.examples.example4;
- 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;
- @PersistJobDataAfterExecution
- @DisallowConcurrentExecution
- public class ColorJob implements Job {
- private static Logger _log = LoggerFactory.getLogger(ColorJob.class);
- public static final String FAVORITE_COLOR = "favorite color";
- public static final String EXECUTION_COUNT = "count";
- private int _counter = 1;
- public ColorJob() {}
- public void execute(JobExecutionContext context)
- throws JobExecutionException {
- JobKey jobKey = context.getJobDetail().getKey();
- 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);
- count++;
- data.put(EXECUTION_COUNT, count);
- _counter++;
- }
- }
控制台输出信息:
- [INFO] 14 六月 10:34:40.640 上午 main [main.java.org.quartz.examples.example4.JobStateExample]
- ------- Initializing -------------------
- [INFO] 14 六月 10:34:40.687 上午 main [org.quartz.impl.StdSchedulerFactory]
- Using default implementation for ThreadExecutor
- [INFO] 14 六月 10:34:40.687 上午 main [org.quartz.simpl.SimpleThreadPool]
- Job execution threads will use class loader of thread: main
- [INFO] 14 六月 10:34:40.718 上午 main [org.quartz.core.SchedulerSignalerImpl]
- Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
- [INFO] 14 六月 10:34:40.718 上午 main [org.quartz.core.QuartzScheduler]
- Quartz Scheduler v.2.1.5 created.
- [INFO] 14 六月 10:34:40.718 上午 main [org.quartz.simpl.RAMJobStore]
- RAMJobStore initialized.
- [INFO] 14 六月 10:34:40.718 上午 main [org.quartz.core.QuartzScheduler]
- Scheduler meta-data: Quartz Scheduler (v2.1.5) 'DefaultQuartzScheduler' 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 10 threads.
- Using job-store 'org.quartz.simpl.RAMJobStore' - which does not support persistence. and is not clustered.
- [INFO] 14 六月 10:34:40.718 上午 main [org.quartz.impl.StdSchedulerFactory]
- Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
- [INFO] 14 六月 10:34:40.718 上午 main [org.quartz.impl.StdSchedulerFactory]
- Quartz scheduler version: 2.1.5
- [INFO] 14 六月 10:34:40.718 上午 main [main.java.org.quartz.examples.example4.JobStateExample]
- ------- Initialization Complete --------
- [INFO] 14 六月 10:34:40.718 上午 main [main.java.org.quartz.examples.example4.JobStateExample]
- ------- Scheduling Jobs ----------------
- [INFO] 14 六月 10:34:40.734 上午 main [main.java.org.quartz.examples.example4.JobStateExample]
- group1.job1 will run at: Thu Jun 14 10:34:50 CST 2012 and repeat: 4 times, every 10 seconds
- [INFO] 14 六月 10:34:40.734 上午 main [main.java.org.quartz.examples.example4.JobStateExample]
- ------- Starting Scheduler ----------------
- [INFO] 14 六月 10:34:40.734 上午 main [org.quartz.core.QuartzScheduler]
- Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
- [INFO] 14 六月 10:34:40.734 上午 main [main.java.org.quartz.examples.example4.JobStateExample]
- ------- Started Scheduler -----------------
- [INFO] 14 六月 10:34:40.734 上午 main [main.java.org.quartz.examples.example4.JobStateExample]
- ------- Waiting 60 seconds... -------------
- [INFO] 14 六月 10:34:50.000 上午 DefaultQuartzScheduler_Worker-1 [main.java.org.quartz.examples.example4.ColorJob]
- ColorJob: group1.job1 executing at Thu Jun 14 10:34:50 CST 2012
- favorite color is Green
- execution count (from job map) is 1
- execution count (from job member variable) is 1
- [INFO] 14 六月 10:35:00.000 上午 DefaultQuartzScheduler_Worker-2 [main.java.org.quartz.examples.example4.ColorJob]
- ColorJob: group1.job1 executing at Thu Jun 14 10:35:00 CST 2012
- favorite color is Green
- execution count (from job map) is 2
- execution count (from job member variable) is 1
- [INFO] 14 六月 10:35:10.015 上午 DefaultQuartzScheduler_Worker-3 [main.java.org.quartz.examples.example4.ColorJob]
- ColorJob: group1.job1 executing at Thu Jun 14 10:35:10 CST 2012
- favorite color is Green
- execution count (from job map) is 3
- execution count (from job member variable) is 1
- [INFO] 14 六月 10:35:20.000 上午 DefaultQuartzScheduler_Worker-4 [main.java.org.quartz.examples.example4.ColorJob]
- ColorJob: group1.job1 executing at Thu Jun 14 10:35:20 CST 2012
- favorite color is Green
- execution count (from job map) is 4
- execution count (from job member variable) is 1
- [INFO] 14 六月 10:35:30.015 上午 DefaultQuartzScheduler_Worker-5 [main.java.org.quartz.examples.example4.ColorJob]
- ColorJob: group1.job1 executing at Thu Jun 14 10:35:30 CST 2012
- favorite color is Green
- execution count (from job map) is 5
- execution count (from job member variable) is 1
- [INFO] 14 六月 10:35:40.734 上午 main [main.java.org.quartz.examples.example4.JobStateExample]
- ------- Shutting Down ---------------------
- [INFO] 14 六月 10:35:40.734 上午 main [org.quartz.core.QuartzScheduler]
- Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutting down.
- [INFO] 14 六月 10:35:40.734 上午 main [org.quartz.core.QuartzScheduler]
- Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED paused.
- [INFO] 14 六月 10:35:41.062 上午 main [org.quartz.core.QuartzScheduler]
- Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutdown complete.
- [INFO] 14 六月 10:35:41.062 上午 main [main.java.org.quartz.examples.example4.JobStateExample]
- ------- Shutdown Complete -----------------
- [INFO] 14 六月 10:35:41.062 上午 main [main.java.org.quartz.examples.example4.JobStateExample]
- Executed 5 jobs.
转载于:https://blog.51cto.com/shuyangyang/898198