quartz-Exception Handling _quartz

Source: Internet
Author: User
Tags dateformat overview example

Overview Example example demonstrates that the example source code

Overview

We follow the official website example to illustrate Quartz's handling when the job performs exceptional conditions.

Refer to the official original:
Http://www.quartz-scheduler.org/documentation/quartz-2.2.x/examples/Example6.html

This article covers 3 classes:
Badjob1.java,
Badjob2.java
Example of a dispatch class Jobexceptionexample.java

Package com.xgj.quartz.quartzItself.exception;
Import Java.text.SimpleDateFormat;

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; /** * * * @ClassName: BADJOB1 * * @Description: setrefireimmediately * * @author: Mr.yang * * @date: 2017 11

    Month 15th morning 1:10:17/@PersistJobDataAfterExecution @DisallowConcurrentExecution public class BadJob1 implements Job { @Override public void Execute (jobexecutioncontext context) throws Jobexecutionexception {Simpleda

        Teformat DateFormat = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
        Jobkey Jobkey = Context.getjobdetail (). Getkey ();

        Jobdatamap Datamap = Context.getjobdetail (). Getjobdatamap ();
        int flag = Datamap.getint ("flag"); System.ouT.PRINTLN ("---" + jobkey + ", Execution time:" + Dateformat.format (new Date ()) + ", flag:" + flag);

        The 0 error divided by the exception that the job will generate (first run only) try {int result = 4815/flag;

            catch (Exception e) {System.out.println ("---Job1 error!");
            Fix the denominator, so the next time this job runs it won't fail jobexecutionexception e2 = new Jobexecutionexception (e);

            Datamap.put ("Flag", "1");

            This job will immediately reboot e2.setrefireimmediately (true);
        throw E2;
    SYSTEM.OUT.PRINTLN ("---" + jobkey + ", Finish time:" + Dateformat.format (new Date ());
 }


}
Package com.xgj.quartz.quartzItself.exception;
Import Java.text.SimpleDateFormat;

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; /** * * * @ClassName: BADJOB2 * * @Description: Setunschedulealltriggers * * @author: Mr.yang * * * @date: 201
    7 November 15 a.m. 1:10:24 */@PersistJobDataAfterExecution @DisallowConcurrentExecution public class BadJob2 implements Job { public void execute (jobexecutioncontext context) throws Jobexecutionexception {SimpleDateFormat da

        Teformat = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
        Jobkey Jobkey = Context.getjobdetail (). Getkey ();

        SYSTEM.OUT.PRINTLN ("---" + jobkey + ", Execution time:" + Dateformat.format (new Date ());

        try {int result = 4815/0; Catch(Exception e)

            {SYSTEM.OUT.PRINTLN ("---job2 error!");
            Quartz automatically cancels all triggers associated with this job so that it no longer runs jobexecutionexception e2 = new Jobexecutionexception (e);

            E2.setunschedulealltriggers (TRUE);
        throw E2;
    SYSTEM.OUT.PRINTLN ("---" + jobkey + ", Finish time:" + Dateformat.format (new Date ());
 }

}
Package com.xgj.quartz.quartzItself.exception;
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 Java.text.SimpleDateFormat;

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; /** * * * @ClassName: Jobexceptionexample * * @Description: Demo Quartz How to handle jobexecutionexceptions thrown from job * * @author: Mr.yang * * @date: November 15, 2017 morning 1:10:02 * * public class Jobexceptionexample {public void run () throws E Xception {//Task Execution time format SimpleDateFormat DateFormat = new SimpleDateFormat ("Yyyy-mm-dd

        HH:mm:ss ");
        Schedulerfactory SF = new Stdschedulerfactory (); Scheduler sched = SF.GEtscheduler ();

        SYSTEM.OUT.PRINTLN ("---------------initialization-------------------");

        Next 15 seconds Date starttime = nextgivenseconddate (null, 15);
                BADJOB1 executes every 10s, throws an exception, and immediately restarts the jobdetail job = Newjob (Badjob1.class). Withidentity ("BadJob1", "group1")
        . Usingjobdata ("flag", "0"). Build (); Simpletrigger trigger = Newtrigger (). Withidentity ("Trigger1", "group1"). StartAt (Starttim
                                e). Withschedule (Simpleschedule (). Withintervalinseconds (10)

        . RepeatForever ()). build ();
        Date ft = sched.schedulejob (job, trigger);
                System.out.println (Job.getkey (). GetName () + "will run at: + dateformat.format (ft) +". and repeat: "

            + trigger.getrepeatcount () + "times, each interval" + trigger.getrepeatinterval ()/1000 + "seconds"); The BADJOB2 executes every 5 seconds, throws an exception, and then no longer executes the job = Newjob (badjob2.class). Withidentity ("BadJob2", "group1"). Build ();
                Trigger = Newtrigger (). Withidentity ("Trigger2", "group1"). StartAt (StartTime) . Withschedule (Simpleschedule (). Withintervalinseconds (5). Rep

        Eatforever ()). build ();

        FT = sched.schedulejob (job, trigger);
                System.out.println (Job.getkey (). GetName () + "will run at: + dateformat.format (ft) +". and repeat: "

        + trigger.getrepeatcount () + "times, each interval" + trigger.getrepeatinterval ()/1000 + "seconds");
        Sched.start ();

        System.out.println ("-------Start dispatch (Invoke. Start () method)----------------");
        try {//Sleep 30s thread.sleep (60L * 1000L);

        catch (Exception e) {} sched.shutdown (false);
        Show the task information that has been performed schedulermetadata MetaData = Sched.getmetadata ();
               System.out.println ("~~~~~~~~~~ executed") + metadata.getnumberofjobsexecuted () + "jobs."); public static void Main (string[] args) throws Exception {Jobexceptionexample example = new Jobexceptionex
        Ample ();
    Example.run ();
 }
}

Run results

INFO stdschedulerfactory-using default implementation for Threadexecutor INFO simplethreadpool-job execution Threads would use class loader of Thread:main INFO schedulersignalerimpl-initialized Scheduler signaller of Type:class
Artz.core.SchedulerSignalerImpl INFO Quartzscheduler-quartz Scheduler v.2.2.3 created.
INFO Ramjobstore-ramjobstore initialized. INFO quartzscheduler-scheduler Meta-data:quartz Scheduler (v2.2.3) ' Defaultquartzscheduler ' with Instanceid ' non_clust
  Ered ' 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 threads. Using job-store ' Org.quartz.simpl.RAMJobStore '-which does not support persistence.

and is not clustered. INFO Stdschedulerfactory-quartz Scheduler ' Defaultquartzscheduler ' initialized from default resource file in Quartz PAC Kage: ' quartz.properties ' INFO stdscheduLerfactory-quartz Scheduler version:2.2.3---------------initialized-------------------BADJOB1 will be run at 01:14:15 2017-11-15. and repeat:-1 times, each interval of 10 seconds badJob2 will be run in: 2017-11-15 01:14:15. and repeat:-1 times, each interval 5 seconds INFO Quartzscheduler-scheduler DEFAULTQ
Uartzscheduler_$_non_clustered started.
-------Start the dispatch (call. Start () method)-------------------group1.badjob1, execution time: 2017-11-15 01:14:15, flag:0---Job1 error!
---group1.badjob2, execution time: 2017-11-15 01:14:15---job2 error! INFO Jobrunshell-job Group1.badjob1 threw a JobExecutionException:org.quartz.JobExecutionException:java.lang.Arithm Eticexception:/By Zero in Com.xgj.quartz.quartzItself.exception.BadJob1.execute (badjob1.java:51) at org.quartz.c Ore. Jobrunshell.run (jobrunshell.java:202) at Org.quartz.simpl.simplethreadpool$workerthread.run ( simplethreadpool.java:573) caused by:java.lang.ArithmeticException:/by zero at Com.xgj.quartz.quartzItself.exceptio N.badjob1.execute (badjob1.java:45) ... 2 common frames omitted INFO Jobrunshell -Job Group1.badjob2 threw a JobExecutionException:org.quartz.JobExecutionException:java.lang.ArithmeticException:/ by zero at Com.xgj.quartz.quartzItself.exception.BadJob2.execute (badjob2.java:44) at ORG.QUARTZ.CORE.JOBRUNSHELL.R Un (jobrunshell.java:202) at Org.quartz.simpl.simplethreadpool$workerthread.run (simplethreadpool.java:573) Caused By:java.lang.ArithmeticException:/By zero at Com.xgj.quartz.quartzItself.exception.BadJob2.execute (Badjob2.java : 38) ... 2 Common frames omitted---group1.badjob1, execution time: 2017-11-15 01:14:15, Flag:1---group1.badjob1, finish time: 2017-11-15 01:14:15- --GROUP1.BADJOB1, Execution time: 2017-11-15 01:14:25, Flag:1---group1.badjob1, completion time: 2017-11-15 01:14:25--- GROUP1.BADJOB1, Execution time: 2017-11-15 01:14:35, Flag:1---group1.badjob1, completion time: 2017-11-15 01:14:35--- GROUP1.BADJOB1, Execution time: 2017-11-15 01:14:45, Flag:1---group1.badjob1, completion time: 2017-11-15 01:14:45--- GROUP1.BADJOB1, Execution time: 2017-11-15 01:14:55, Flag:1---group1.badjob1, finish time: 2017-11-15 01:14:55---group1.BADJOB1, Execution time: 2017-11-15 01:15:05, Flag:1---group1.badjob1, finish time: 2017-11-15 01:15:05 INFO Quartzscheduler-scheduler De
Faultquartzscheduler_$_non_clustered shutting down.
INFO Quartzscheduler-scheduler defaultquartzscheduler_$_non_clustered paused.
INFO Quartzscheduler-scheduler defaultquartzscheduler_$_non_clustered shutdown complete.
 ~~~~~~~~~~ carried out 8 jobs.
Example description

JOB1: After throwing an exception, then set the flag to 1, that is, only the first time there will be exceptions thrown, after the normal code

   Setrefireimmediately (TRUE); It sets how the job class is handled after it throws an exception, meaning that it is executed immediately after an exception occurs

JOB2: Unlike JOB1, it does not judge, and throws one exception at a time.

   E2.setunschedulealltriggers (true), setting the trigger to remove it, means that BadJob2 if an exception occurs, there is no chance of executing
Description

What happens if the exception in Job1.java and Job2.java is not thrown (commented out)?

Job1 if not thrown: perform normally because there is a restart job statement in exception handling

Job2 if not thrown: The task executes every time, and each time it enters an exception. The equivalent of the subsequent task does not stop. Sample source Code

Code is hosted to Github-> Https://github.com/yangshangwei/SpringMaster

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.