Use job listeners to have one job trigger another job, building a simple workflow
示例:通过Listener实例流程执行,创建一个Listener对Job1进行监听,当Job1执完成时,执行Job2(通过void jobWasExecuted(JobExecutionContext inContext, JobExecutionException inException)监听,在其方法中写执行Job2的代码,实现通过Listener在Job1完成后,自动执行Job2任务。
Job1
------------------------------------------------------------------------------------------------------------
/*
* 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.example9;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* This is just a simple job that gets fired off many times by example 1
* </p>
*
* @author Bill Kratzer
*/
public class SimpleJob1 implements Job {
private static Logger _log = LoggerFactory.getLogger(SimpleJob1.class);
/**
* Empty constructor for job initilization
*/
public SimpleJob1() {
}
/**
* <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();
_log.info("SimpleJob1 says: " + jobKey + " executing at " + new Date());
}
}
------------------------------------------------------------------------------------------------------------
Job2
------------------------------------------------------------------------------------------------------------
/*
* 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.example9;
import java.util.Date;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* This is just a simple job that gets fired off many times by example 1
* </p>
*
* @author Bill Kratzer
*/
public class SimpleJob2 implements Job {
private static Logger _log = LoggerFactory.getLogger(SimpleJob2.class);
/**
* Empty constructor for job initialization
*/
public SimpleJob2() {
}
/**
* <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();
_log.info("SimpleJob2 says: " + jobKey + " executing at " + new Date());
}
}
------------------------------------------------------------------------------------------------------------
Listener:jobWasExecuted()方法中写执行Job2的代码
------------------------------------------------------------------------------------------------------------
/*
* 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.example9;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author wkratzer
*/
public class Job1Listener implements JobListener {
private static Logger _log = LoggerFactory.getLogger(Job1Listener.class);
public String getName() {
return "job1_to_job2";
}
public void jobToBeExecuted(JobExecutionContext inContext) {
_log.info("Job1Listener says: Job Is about to be executed.");
}
public void jobExecutionVetoed(JobExecutionContext inContext) {
_log.info("Job1Listener says: Job Execution was vetoed.");
}
public void jobWasExecuted(JobExecutionContext inContext, JobExecutionException inException) {
_log.info("Job1Listener says: Job was executed.");
// Simple job #2
JobDetail job2 = newJob(SimpleJob2.class).withIdentity("job2").build();
Trigger trigger = newTrigger().withIdentity("job2Trigger").startNow().build();
try {
// schedule the job to run!
inContext.getScheduler().scheduleJob(job2, trigger);
} catch (SchedulerException e) {
_log.warn("Unable to schedule job2!");
e.printStackTrace();
}
}
}
------------------------------------------------------------------------------------------------------------
Main:将Job1与Listener关联,监听Job1执行情况
------------------------------------------------------------------------------------------------------------
/*
* 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.example9;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.JobListener;
import org.quartz.Matcher;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SchedulerMetaData;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.KeyMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Demonstrates the behavior of <code>JobListener</code>s. In particular, this example will use a job listener to
* trigger another job after one job succesfully executes.
*/
public class ListenerExample {
public void run() throws Exception {
Logger log = LoggerFactory.getLogger(ListenerExample.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 -------------------");
// schedule a job to run immediately
JobDetail job = newJob(SimpleJob1.class).withIdentity("job1").build();
Trigger trigger = newTrigger().withIdentity("trigger1").startNow().build();
// Set up the listener
JobListener listener = new Job1Listener();
Matcher<JobKey> matcher = KeyMatcher.keyEquals(job.getKey());
sched.getListenerManager().addJobListener(listener, matcher);
// schedule the job to run
sched.scheduleJob(job, trigger);
// All of the jobs have been added to the scheduler, but none of the jobs
// will run until the scheduler has been started
log.info("------- Starting Scheduler ----------------");
sched.start();
// wait 30 seconds:
// note: nothing will run
log.info("------- Waiting 30 seconds... --------------");
try {
// wait 30 seconds to show jobs
Thread.sleep(30L * 1000L);
// executing...
} catch (Exception e) {
//
}
// shut down the scheduler
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 {
ListenerExample example = new ListenerExample();
example.run();
}
}
------------------------------------------------------------------------------------------------------------
Executing result:在Job1执行完后,Job2自动执行
16:48:17.808 INFO org.quartz.examples.example9.ListenerExample 45 run - ------- Initializing ----------------------
16:48:17.868 INFO org.quartz.impl.StdSchedulerFactory 1172 instantiate - Using default implementation for ThreadExecutor
16:48:17.871 INFO org.quartz.simpl.SimpleThreadPool 268 initialize - Job execution threads will use class loader of thread: main
16:48:17.884 INFO org.quartz.core.SchedulerSignalerImpl 61 <init> - Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
16:48:17.884 INFO org.quartz.core.QuartzScheduler 240 <init> - Quartz Scheduler v.2.2.3 created.
16:48:17.885 INFO org.quartz.simpl.RAMJobStore 155 initialize - RAMJobStore initialized.
16:48:17.887 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.
16:48:17.887 INFO org.quartz.impl.StdSchedulerFactory 1327 instantiate - Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
16:48:17.888 INFO org.quartz.impl.StdSchedulerFactory 1331 instantiate - Quartz scheduler version: 2.2.3
16:48:17.888 INFO org.quartz.examples.example9.ListenerExample 51 run - ------- Initialization Complete -----------
16:48:17.888 INFO org.quartz.examples.example9.ListenerExample 53 run - ------- Scheduling Jobs -------------------
16:48:17.895 INFO org.quartz.examples.example9.ListenerExample 71 run - ------- Starting Scheduler ----------------
16:48:17.895 INFO org.quartz.core.QuartzScheduler 575 start - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
16:48:17.895 INFO org.quartz.examples.example9.ListenerExample 76 run - ------- Waiting 30 seconds... --------------
16:48:17.900 INFO org.quartz.examples.example9.Job1Listener 44 jobToBeExecuted - Job1Listener says: Job Is about to be executed.
16:48:17.901 INFO org.quartz.examples.example9.SimpleJob1 62 execute - SimpleJob1 says: DEFAULT.job1 executing at Mon Aug 13 16:48:17 CST 2018
16:48:17.901 INFO org.quartz.examples.example9.Job1Listener 52 jobWasExecuted - Job1Listener says: Job was executed.
16:48:17.904 INFO org.quartz.examples.example9.SimpleJob2 62 execute - SimpleJob2 says: DEFAULT.job2 executing at Mon Aug 13 16:48:17 CST 2018
16:48:47.897 INFO org.quartz.examples.example9.ListenerExample 86 run - ------- Shutting Down ---------------------
16:48:47.897 INFO org.quartz.core.QuartzScheduler 694 shutdown - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutting down.
16:48:47.897 INFO org.quartz.core.QuartzScheduler 613 standby - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED paused.
16:48:47.941 INFO org.quartz.core.QuartzScheduler 771 shutdown - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutdown complete.
16:48:47.942 INFO org.quartz.examples.example9.ListenerExample 88 run - ------- Shutdown Complete -----------------
16:48:47.942 INFO org.quartz.examples.example9.ListenerExample 91 run - Executed 2 jobs.