
来源
:自动重试Quartz中失败的作业
如果您想要一项不断尝试直到成功的工作,您要做的就是抛出一个带有标志的JobExecutionException,以通知调度程序在失败时再次触发它。以下代码显示了如何:
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; } }}如果要重试一定次数,它将变得更加复杂。您必须使用StatefulJob并将retryCounter保留在其JobDataMap中,如果作业失败,则将其递增。如果计数器超过最大重试次数,则可以根据需要禁用该作业。
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; } }}欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)