Quartz 之 处理Job 异常

Posted 秋风小凉鱼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Quartz 之 处理Job 异常相关的知识,希望对你有一定的参考价值。

项目地址:  

         https://github.com/yuleiqq/quartz_example/tree/master/quartz_study

此示例旨在演示如何处理作业执行异常。允许Quartz中的作业抛出jobexecutionexception异常。当抛出此异常时,您可以指示quartz采取什么操作。

程序将执行以下操作:

  • 启动Quartz 调度器
  • 调度两个作业,每个作业将不确定地每三秒执行一次
  • 作业将抛出一个异常,quartz将采取适当的操作
  • 程序将等待60秒,以便两个作业有足够的时间运行
  • 关闭调度程序

代码位置在包:com.example07 

BadJob1是一个简单的任务,它只创建一个人工异常(除以0)。当捕获此异常时,将抛出一个JobExecutionException并设置为立即重新启动该作业。

 try 
            int zero = 0;
            int calculation = 4815 / zero;
        
        catch (Exception e) 
        	_log.info("--- Error in job!");
        	JobExecutionException e2 =
        		new JobExecutionException(e);
        	// this job will refire immediately
        	e2.refireImmediately();
        	throw e2;
        

这将迫使quartz一次又一次、一次又一次地运行这个作业。

BadJob2是一个简单的任务,它只创建一个人工异常(除以0)。当捕获此异常时,将抛出并设置JobExecutionException,以确保quartz不再运行该作业。

     try 
            int zero = 0;
            int 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;
        

这将迫使quartz关闭该作业,以便不再运行。

如下是JobExample的内容


 
package com.example07;

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();
  


运行该类,打印如下内容:

[INFO] 10 七月 05:41:07.273 下午 main [com.example07.JobExceptionExample]
------- Initializing ----------------------

[INFO] 10 七月 05:41:07.304 下午 main [org.quartz.impl.StdSchedulerFactory]
Using default implementation for ThreadExecutor

[INFO] 10 七月 05:41:07.335 下午 main [org.quartz.core.SchedulerSignalerImpl]
Initialized Scheduler Signaller of type: class org.quartz.core.SchedulerSignalerImpl

[INFO] 10 七月 05:41:07.335 下午 main [org.quartz.core.QuartzScheduler]
Quartz Scheduler v.2.3.0 created.

[INFO] 10 七月 05:41:07.335 下午 main [org.quartz.simpl.RAMJobStore]
RAMJobStore initialized.

[INFO] 10 七月 05:41:07.335 下午 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] 10 七月 05:41:07.335 下午 main [org.quartz.impl.StdSchedulerFactory]
Quartz scheduler 'MyScheduler' initialized from default resource file in Quartz package: 'quartz.properties'

[INFO] 10 七月 05:41:07.335 下午 main [org.quartz.impl.StdSchedulerFactory]
Quartz scheduler version: 2.3.0

[INFO] 10 七月 05:41:07.335 下午 main [com.example07.JobExceptionExample]
------- Initialization Complete ------------

[INFO] 10 七月 05:41:07.335 下午 main [com.example07.JobExceptionExample]
------- Scheduling Jobs -------------------

[INFO] 10 七月 05:41:07.335 下午 main [com.example07.JobExceptionExample]
group1.badJob1 will run at: Fri Jul 10 17:41:15 CST 2020 and repeat: -1 times, every 10 seconds

[INFO] 10 七月 05:41:07.351 下午 main [com.example07.JobExceptionExample]
group1.badJob2 will run at: Fri Jul 10 17:41:15 CST 2020 and repeat: -1 times, every 5 seconds

[INFO] 10 七月 05:41:07.351 下午 main [com.example07.JobExceptionExample]
------- Starting Scheduler ----------------

[INFO] 10 七月 05:41:07.351 下午 main [org.quartz.core.QuartzScheduler]
Scheduler MyScheduler_$_NON_CLUSTERED started.

[INFO] 10 七月 05:41:07.351 下午 main [com.example07.JobExceptionExample]
------- Started Scheduler -----------------

[INFO] 10 七月 05:41:15.000 下午 MyScheduler_Worker-1 [com.example07.BadJob1]
---group1.badJob1 executing at Fri Jul 10 17:41:15 CST 2020 with denominator 0

[INFO] 10 七月 05:41:15.000 下午 MyScheduler_Worker-1 [com.example07.BadJob1]
--- Error in job!

[INFO] 10 七月 05:41:15.000 下午 MyScheduler_Worker-2 [com.example07.BadJob2]
---group1.badJob2 executing at Fri Jul 10 17:41:15 CST 2020

[INFO] 10 七月 05:41:15.000 下午 MyScheduler_Worker-2 [com.example07.BadJob2]
--- Error in job!

[INFO] 10 七月 05:41:15.000 下午 MyScheduler_Worker-1 [org.quartz.core.JobRunShell]
Job group1.badJob1 threw a JobExecutionException: 

org.quartz.JobExecutionException: java.lang.ArithmeticException: / by zero [See nested exception: java.lang.ArithmeticException: / by zero]
	at com.example07.BadJob1.execute(BadJob1.java:75)
	at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
	at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)
Caused by: java.lang.ArithmeticException: / by zero
	at com.example07.BadJob1.execute(BadJob1.java:72)
	... 2 more
[INFO] 10 七月 05:41:15.000 下午 MyScheduler_Worker-2 [org.quartz.core.JobRunShell]
Job group1.badJob2 threw a JobExecutionException: 

org.quartz.JobExecutionException: java.lang.ArithmeticException: / by zero [See nested exception: java.lang.ArithmeticException: / by zero]
	at com.example07.BadJob2.execute(BadJob2.java:74)
	at org.quartz.core.JobRunShell.run(JobRunShell.java:202)
	at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573)
Caused by: java.lang.ArithmeticException: / by zero
	at com.example07.BadJob2.execute(BadJob2.java:71)
	... 2 more
[INFO] 10 七月 05:41:15.000 下午 MyScheduler_Worker-1 [com.example07.BadJob1]
---group1.badJob1 executing at Fri Jul 10 17:41:15 CST 2020 with denominator 1

[INFO] 10 七月 05:41:15.016 下午 MyScheduler_Worker-1 [com.example07.BadJob1]
---group1.badJob1 completed at Fri Jul 10 17:41:15 CST 2020

[INFO] 10 七月 05:41:25.008 下午 MyScheduler_Worker-3 [com.example07.BadJob1]
---group1.badJob1 executing at Fri Jul 10 17:41:25 CST 2020 with denominator 1

[INFO] 10 七月 05:41:25.008 下午 MyScheduler_Worker-3 [com.example07.BadJob1]
---group1.badJob1 completed at Fri Jul 10 17:41:25 CST 2020

[INFO] 10 七月 05:41:35.007 下午 MyScheduler_Worker-4 [com.example07.BadJob1]
---group1.badJob1 executing at Fri Jul 10 17:41:35 CST 2020 with denominator 1

[INFO] 10 七月 05:41:35.007 下午 MyScheduler_Worker-4 [com.example07.BadJob1]
---group1.badJob1 completed at Fri Jul 10 17:41:35 CST 2020

[INFO] 10 七月 05:41:37.357 下午 main [com.example07.JobExceptionExample]
------- Shutting Down ---------------------

[INFO] 10 七月 05:41:37.357 下午 main [org.quartz.core.QuartzScheduler]
Scheduler MyScheduler_$_NON_CLUSTERED shutting down.

[INFO] 10 七月 05:41:37.357 下午 main [org.quartz.core.QuartzScheduler]
Scheduler MyScheduler_$_NON_CLUSTERED paused.

[INFO] 10 七月 05:41:37.357 下午 main [org.quartz.core.QuartzScheduler]
Scheduler MyScheduler_$_NON_CLUSTERED shutdown complete.

[INFO] 10 七月 05:41:37.357 下午 main [com.example07.JobExceptionExample]
------- Shutdown Complete -----------------

[INFO] 10 七月 05:41:37.357 下午 main [com.example07.JobExceptionExample]
Executed 5 jobs.

 

 

以上是关于Quartz 之 处理Job 异常的主要内容,如果未能解决你的问题,请参考以下文章

Quartz 之 Job参数 和 Job状态

Quartz 之 Job Misfires

Quartz之Job与JobDetail浅析

quartz2.3.0job任务监听器,监听任务执行前后取消手动处理方法

SpringBoot之Quartz实战

关于quartz的同步处理问题