No job is perfect. See how you can let the scheduler know how to deal with exceptions that are thrown by your job
要点:
在执行Job的时候,有可能会发现异常,对于这情况我们如何处理?
1.必须要在Job类型使用try…..catch,而不要抛出异常,因为抛出异常会造成任务一直循环执行。
2.遇到异常后,在catch中修改产生异常的数据为正常(即不会再产生异常)到JobDataMap中,并让Job马上重新触发一次,让任务不再抛异常,任务执行结束。
3.遇到异常后,将该Job关联的所有Trigger的scheduler全部取消(通过抛JobExecutionException异常实现),使该Job不会再被触发,避免异常。
------------------------------------------------------------------------------------------------------------
/*
* 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.example6;
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;
import java.util.Date;
/**
* <p>
* A job dumb job that will throw a job execution exception
* </p>
*
* @author Bill Kratzer
*/
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class BadJob1 implements Job {
// Logging
private static Logger _log = LoggerFactory.getLogger(BadJob1.class);
private int calculation;
/**
* Empty public constructor for job initialization
*/
public BadJob1() {
}
/**
* <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 {
JobKey jobKey = context.getJobDetail().getKey();
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
int denominator = dataMap.getInt("denominator");
_log.info("---" + jobKey + " executing at " + new Date() + " with denominator " + denominator);
// a contrived example of an exception that
// will be generated by this job due to a
// divide by zero error (only on first run)
try {
calculation = 4815 / denominator;
} catch (Exception e) {
_log.info("--- Error in job!");
JobExecutionException e2 = new JobExecutionException(e);
// fix denominator so the next time this job run
// it won't fail again
dataMap.put("denominator", "1");
// this job will refire immediately
e2.setRefireImmediately(true);
throw e2;
}
_log.info("---" + jobKey + " completed at " + new Date());
}
}
------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
/*
* 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.example6;
import java.util.Date;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
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>
* A job dumb job that will throw a job execution exception
* </p>
*
* @author Bill Kratzer
*/
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
public class BadJob2 implements Job {
// Logging
private static Logger _log = LoggerFactory.getLogger(BadJob2.class);
private int calculation;
/**
* Empty public constructor for job initialization
*/
public BadJob2() {
}
/**
* <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 {
JobKey jobKey = context.getJobDetail().getKey();
_log.info("---" + jobKey + " executing at " + new Date());
// a contrived example of an exception that
// will be generated by this job due to a
// divide by zero error
try {
int zero = 0;
calculation = 4815 / zero;
} catch (Exception e) {
_log.info("--- Error in job!");
JobExecutionException e2 =
new JobExecutionException(e);
// Quartz will automatically unschedule
// all triggers associated with this job
// so that it does not run again
e2.setUnscheduleAllTriggers(true);
throw e2;
}
_log.info("---" + jobKey + " completed at " + new Date());
}
}
------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------
/*
* 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.example6;
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 job demonstrates how Quartz can handle JobExecutionExceptions that are thrown by jobs.
*
* @author Bill Kratzer
*/
public class JobExceptionExample {
public void run() throws Exception {
Logger log = LoggerFactory.getLogger(JobExceptionExample.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 start() has been called
// get a "nice round" time a few seconds in the future...
Date startTime = nextGivenSecondDate(null, 15);
// badJob1 will run every 10 seconds
// this job will throw an exception and refire
// immediately
JobDetail job = newJob(BadJob1.class).withIdentity("badJob1", "group1").usingJobData("denominator", "0").build();
SimpleTrigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(startTime)
.withSchedule(simpleSchedule().withIntervalInSeconds(10).repeatForever()).build();
Date ft = sched.scheduleJob(job, trigger);
log.info(job.getKey() + " will run at: " + ft + " and repeat: " + trigger.getRepeatCount() + " times, every "
+ trigger.getRepeatInterval() / 1000 + " seconds");
// badJob2 will run every five seconds
// this job will throw an exception and never
// refire
job = newJob(BadJob2.class).withIdentity("badJob2", "group1").build();
trigger = newTrigger().withIdentity("trigger2", "group1").startAt(startTime)
.withSchedule(simpleSchedule().withIntervalInSeconds(5).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 ----------------");
// jobs don't start firing until start() has been called...
sched.start();
log.info("------- Started Scheduler -----------------");
try {
// sleep for 30 seconds
Thread.sleep(30L * 1000L);
} catch (Exception e) {
//
}
log.info("------- Shutting Down ---------------------");
sched.shutdown(false);
log.info("------- Shutdown Complete -----------------");
SchedulerMetaData metaData = sched.getMetaData();
log.info("Executed " + metaData.getNumberOfJobsExecuted() + " jobs.");
}
public static void main(String[] args) throws Exception {
JobExceptionExample example = new JobExceptionExample();
example.run();
}
}
------------------------------------------------------------------------------------------------------------
Executing result:
22:57:34.853 INFO org.quartz.examples.example6.JobExceptionExample 46 run - ------- Initializing ----------------------
22:57:34.911 INFO org.quartz.impl.StdSchedulerFactory 1172 instantiate - Using default implementation for ThreadExecutor
22:57:34.915 INFO org.quartz.simpl.SimpleThreadPool 268 initialize - Job execution threads will use class loader of thread: main
22:57:34.929 INFO org.quartz.core.SchedulerSignalerImpl 61 <init> - Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl
22:57:34.930 INFO org.quartz.core.QuartzScheduler 240 <init> - Quartz Scheduler v.2.2.3 created.
22:57:34.931 INFO org.quartz.simpl.RAMJobStore 155 initialize - RAMJobStore initialized.
22:57:34.932 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.
22:57:34.932 INFO org.quartz.impl.StdSchedulerFactory 1327 instantiate - Quartz scheduler 'DefaultQuartzScheduler' initialized from default resource file in Quartz package: 'quartz.properties'
22:57:34.932 INFO org.quartz.impl.StdSchedulerFactory 1331 instantiate - Quartz scheduler version: 2.2.3
22:57:34.933 INFO org.quartz.examples.example6.JobExceptionExample 52 run - ------- Initialization Complete ------------
22:57:34.933 INFO org.quartz.examples.example6.JobExceptionExample 54 run - ------- Scheduling Jobs -------------------
22:57:34.941 INFO org.quartz.examples.example6.JobExceptionExample 70 run - group1.badJob1 will run at: Sun Aug 12 22:57:45 CST 2018 and repeat: -1 times, every 10 seconds
22:57:34.942 INFO org.quartz.examples.example6.JobExceptionExample 82 run - group1.badJob2 will run at: Sun Aug 12 22:57:45 CST 2018 and repeat: -1 times, every 5 seconds
22:57:34.942 INFO org.quartz.examples.example6.JobExceptionExample 85 run - ------- Starting Scheduler ----------------
22:57:34.942 INFO org.quartz.core.QuartzScheduler 575 start - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED started.
22:57:34.943 INFO org.quartz.examples.example6.JobExceptionExample 90 run - ------- Started Scheduler -----------------
22:57:45.024 INFO org.quartz.examples.example6.BadJob1 66 execute - ---group1.badJob1 executing at Sun Aug 12 22:57:45 CST 2018 with denominator 0
22:57:45.024 INFO org.quartz.examples.example6.BadJob1 74 execute - --- Error in job!
22:57:45.046 INFO org.quartz.examples.example6.BadJob2 64 execute - ---group1.badJob2 executing at Sun Aug 12 22:57:45 CST 2018
22:57:45.047 INFO org.quartz.examples.example6.BadJob2 73 execute - --- Error in job!
22:57:45.047 INFO org.quartz.core.JobRunShell 207 run - Job group1.badJob2 threw a JobExecutionException: org.quartz.JobExecutionException: java.lang.ArithmeticException: / by zero
at org.quartz.examples.example6.BadJob2.execute(BadJob2.java:75) ~[test-classes/:?]
at org.quartz.core.JobRunShell.run(JobRunShell.java:202) [quartz-2.2.3.jar:?]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) [quartz-2.2.3.jar:?]
Caused by: java.lang.ArithmeticException: / by zero
at org.quartz.examples.example6.BadJob2.execute(BadJob2.java:71) ~[test-classes/:?]
... 2 more
22:57:45.024 INFO org.quartz.core.JobRunShell 207 run - Job group1.badJob1 threw a JobExecutionException: org.quartz.JobExecutionException: java.lang.ArithmeticException: / by zero
at org.quartz.examples.example6.BadJob1.execute(BadJob1.java:75) ~[test-classes/:?]
at org.quartz.core.JobRunShell.run(JobRunShell.java:202) [quartz-2.2.3.jar:?]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) [quartz-2.2.3.jar:?]
Caused by: java.lang.ArithmeticException: / by zero
at org.quartz.examples.example6.BadJob1.execute(BadJob1.java:72) ~[test-classes/:?]
... 2 more
22:57:45.049 INFO org.quartz.examples.example6.BadJob1 66 execute - ---group1.badJob1 executing at Sun Aug 12 22:57:45 CST 2018 with denominator 1
22:57:45.049 INFO org.quartz.examples.example6.BadJob1 86 execute - ---group1.badJob1 completed at Sun Aug 12 22:57:45 CST 2018
22:57:55.002 INFO org.quartz.examples.example6.BadJob1 66 execute - ---group1.badJob1 executing at Sun Aug 12 22:57:55 CST 2018 with denominator 1
22:57:55.005 INFO org.quartz.examples.example6.BadJob1 86 execute - ---group1.badJob1 completed at Sun Aug 12 22:57:55 CST 2018
22:58:04.943 INFO org.quartz.examples.example6.JobExceptionExample 99 run - ------- Shutting Down ---------------------
22:58:04.945 INFO org.quartz.core.QuartzScheduler 694 shutdown - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutting down.
22:58:04.948 INFO org.quartz.core.QuartzScheduler 613 standby - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED paused.
22:58:04.951 INFO org.quartz.core.QuartzScheduler 771 shutdown - Scheduler DefaultQuartzScheduler_$_NON_CLUSTERED shutdown complete.
22:58:04.954 INFO org.quartz.examples.example6.JobExceptionExample 103 run - ------- Shutdown Complete -----------------
22:58:04.967 INFO org.quartz.examples.example6.JobExceptionExample 106 run - Executed 4 jobs.