Demonstrates how parameters can be passed into jobs and how jobs maintain state
------------------------------------------------------------------------------------------------------------
/*
* 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.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;
/**
* <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++;
}
}
------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
/*
* 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.example4;
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();
}
}
------------------------------------------------------------------------------------------------------------
Executing result:
17:13:50.663 INFO org.quartz.examples.example4.JobStateExample 46 run - ------- Initializing -------------------
17:13:50.725 INFO org.quartz.impl.StdSchedulerFactory 1172 instantiate - Using default implementation for ThreadExecutor
17:13:50.728 INFO org.quartz.simpl.SimpleThreadPool 268 initialize - Job execution threads will use class loader of thread: main
17:13:50.742 INFO org.quartz.core.SchedulerSignalerImpl 61 <init> - Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
17:13:50.742 INFO org.quartz.core.QuartzScheduler 240 <init> - Quartz Scheduler v.2.2.3 created.
17:13:50.743 INFO org.quartz.simpl.RAMJobStore 155 initialize - RAMJobStore initialized.
17:13:50.744 INFO org.quartz.core.QuartzScheduler 305 initialize - Scheduler meta-data: Quartz Scheduler (v2.2.3) '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.
17:13:50.745 INFO org.quartz.impl.StdSchedulerFactory 1327 instantiate - Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
17:13:50.746 INFO org.quartz.impl.StdSchedulerFactory 1331 instantiate - Quartz scheduler version: 2.2.3
17:13:50.746 INFO org.quartz.examples.example4.JobStateExample 52 run - ------- Initialization Complete --------
17:13:50.746 INFO org.quartz.examples.example4.JobStateExample 54 run - ------- Scheduling Jobs ----------------
17:13:50.754 INFO org.quartz.examples.example4.JobStateExample 75 run - group1.job1 will run at: Sun Aug 12 17:14:00 CST 2018 and repeat: 4 times, every 10 seconds
17:13:50.755 INFO org.quartz.examples.example4.JobStateExample 95 run - group1.job2 will run at: Sun Aug 12 17:14:00 CST 2018 and repeat: 4 times, every 10 seconds
17:13:50.755 INFO org.quartz.examples.example4.JobStateExample 98 run - ------- Starting Scheduler ----------------
17:13:50.756 INFO org.quartz.core.QuartzScheduler 575 start - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
17:13:50.756 INFO org.quartz.examples.example4.JobStateExample 104 run - ------- Started Scheduler -----------------
17:13:50.757 INFO org.quartz.examples.example4.JobStateExample 106 run - ------- Waiting 60 seconds... -------------
17:14:00.113 INFO org.quartz.examples.example4.ColorJob 88 execute - ColorJob: group1.job1 executing at Sun Aug 12 17:14:00 CST 2018
favorite color is Green
execution count (from job map) is 1
execution count (from job member variable) is 1
17:14:00.118 INFO org.quartz.examples.example4.ColorJob 88 execute - ColorJob: group1.job2 executing at Sun Aug 12 17:14:00 CST 2018
favorite color is Red
execution count (from job map) is 1
execution count (from job member variable) is 1
17:14:10.002 INFO org.quartz.examples.example4.ColorJob 88 execute - ColorJob: group1.job2 executing at Sun Aug 12 17:14:10 CST 2018
favorite color is Red
execution count (from job map) is 2
execution count (from job member variable) is 1
17:14:10.002 INFO org.quartz.examples.example4.ColorJob 88 execute - ColorJob: group1.job1 executing at Sun Aug 12 17:14:10 CST 2018
favorite color is Green
execution count (from job map) is 2
execution count (from job member variable) is 1
17:14:20.003 INFO org.quartz.examples.example4.ColorJob 88 execute - ColorJob: group1.job2 executing at Sun Aug 12 17:14:20 CST 2018
favorite color is Red
execution count (from job map) is 3
execution count (from job member variable) is 1
17:14:20.011 INFO org.quartz.examples.example4.ColorJob 88 execute - ColorJob: group1.job1 executing at Sun Aug 12 17:14:20 CST 2018
favorite color is Green
execution count (from job map) is 3
execution count (from job member variable) is 1