Quartz retry when failure

后端 未结 3 1333
礼貌的吻别
礼貌的吻别 2020-12-07 18:12

Let\'s say I have a trigger configured this way:



        
3条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 18:39

    Source: Automatically Retry Failed Jobs in Quartz

    If you want to have a job which keeps trying over and over again until it succeeds, all you have to do is throw a JobExecutionException with a flag to tell the scheduler to fire it again when it fails. The following code shows how:

    class MyJob implements Job {
    
        public MyJob() {
        }
    
        public void execute(JobExecutionContext context) throws JobExecutionException {
    
            try{
                //connect to other application etc
            }
            catch(Exception e){
    
                Thread.sleep(600000); //sleep for 10 mins
    
                JobExecutionException e2 = new JobExecutionException(e);
                //fire it again
                e2.setRefireImmediately(true);
                throw e2;
            }
        }
    }
    

    It gets a bit more complicated if you want to retry a certain number of times. You have to use a StatefulJob and hold a retryCounter in its JobDataMap, which you increment if the job fails. If the counter exceeds the maximum number of retries, then you can disable the job if you wish.

    class MyJob implements StatefulJob {
    
        public MyJob() {
        }
    
        public void execute(JobExecutionContext context) throws JobExecutionException {
            JobDataMap dataMap = context.getJobDetail().getJobDataMap();
            int count = dataMap.getIntValue("count");
    
            // allow 5 retries
            if(count >= 5){
                JobExecutionException e = new JobExecutionException("Retries exceeded");
                //make sure it doesn't run again
                e.setUnscheduleAllTriggers(true);
                throw e;
            }
    
    
            try{
                //connect to other application etc
    
                //reset counter back to 0
                dataMap.putAsString("count", 0);
            }
            catch(Exception e){
                count++;
                dataMap.putAsString("count", count);
                JobExecutionException e2 = new JobExecutionException(e);
    
                Thread.sleep(600000); //sleep for 10 mins
    
                //fire it again
                e2.setRefireImmediately(true);
                throw e2;
            }
        }
    }
    

提交回复
热议问题