Подобные вопросы, кажется, задавались много раз, но я все еще не могу найти точный ответ. Я использую org.quartz.StatefulJob, чтобы настроить запланированное задание, чтобы повторить его 5 раз, имитируя Exception и Spring cron для вызвать его, но произошло исключение, вот подробности:
@Service(value = "cronJobRetryImpl")
public class DuMiSynchronizationRetryRest implements StatefulJob {
private Logger logger = Logger.getLogger(getClass());
@Override
public void execute(JobExecutionContext context) throws
JobExecutionException {
logger.info("enter execute ...");
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
long count =
NumberUtils.toLong(String.valueOf(dataMap.get("count")));
if (count >= 5) {
logger.info("Retries exceeded...");
JobExecutionException e = new JobExecutionException("Retries
exceeded");
e.setUnscheduleAllTriggers(true);
throw e;
}
try {
logger.info("business begin...");
dataMap.put("count", 0);
int n = 10 / 0;
} catch (Exception e) {
count++;
dataMap.putAsString("count", count);
JobExecutionException e2 = new JobExecutionException(e);
try {
logger.info("Thread begin to sleep for 3 seconds...");
Thread.sleep(3000);
} catch (InterruptedException e1) {
logger.info("interrupted exception",e1);
}
e2.refireImmediately();
logger.info("job refired ...");
throw e2;
}
}
}
Вот весна xml:
<!-- retry test start -->
<bean id="cronJobRetryImplTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" lazy-init="true">
<property name="targetObject">
<ref bean="cronJobRetryImpl" />
</property>
<property name="targetMethod">
<value>execute</value>
</property>
<property name="concurrent" value="false" />
</bean>
<bean id="cronJobRetryTime" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail">
<ref bean="cronJobRetryImplTask" />
</property>
<property name="cronExpression">
<value>20 30 9 * * ?</value>
</property>
</bean>
<!-- retry test end -->
<bean id="startQuertz" lazy-init="false" autowire="no"
class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<list>
<ref bean="cronJobRetryTime" />
</list>
</property>
Я планировал запускать его каждый 9:30:20, и результат:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cronJobRetryTime' defined in class path resource [applicationContext-job.xml]: Cannot resolve reference to bean 'cronJobRetryImplTask' while setting bean property 'jobDetail'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cronJobRetryImplTask' defined in class path resource [applicationContext-job.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodException: tv.huan.cms.services.rest.DuMiSynchronizationRetryRest.execute()
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1360)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:607)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:925)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:472)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:388)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:293)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5157)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5680)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:145)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1702)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1692)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cronJobRetryImplTask' defined in class path resource [applicationContext-job.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodException: tv.huan.cms.services.rest.DuMiSynchronizationRetryRest.execute()
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
... 24 more
Caused by: java.lang.NoSuchMethodException: tv.huan.cms.services.rest.DuMiSynchronizationRetryRest.execute()
at java.lang.Class.getMethod(Unknown Source)
at org.springframework.util.MethodInvoker.prepare(MethodInvoker.java:178)
at org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean.afterPropertiesSet(MethodInvokingJobDetailFactoryBean.java:198)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
... 31 more
----------------------- первое редактирование ---------------------- -----
Да, да, воспроизведение samabcde эффективно, и спасибо samabcde за ваше терпение и усилия, но, похоже, проблемы в самом коде. Я пытаюсь запустить эти коды, но задание не может быть выполнено снова, когда имитируется исключение:
INFO 2018-11-02 14:43:00,022 [DuMiSynchronizationRetryRest.java,16] - enter
execute ...
INFO 2018-11-02 14:43:00,027 [DuMiSynchronizationRetryRest.java,28] -
business begin...
INFO 2018-11-02 14:43:00,027 [DuMiSynchronizationRetryRest.java,36] -
Thread begin to sleep for 3 seconds...
INFO 2018-11-02 14:43:03,028 [DuMiSynchronizationRetryRest.java,42] - job
refired ...
INFO 2018-11-02 14:43:03,031 [JobRunShell.java,221] - Job
DEFAULT.cronJobRetryImplTask threw a JobExecutionException:
org.quartz.JobExecutionException: java.lang.ArithmeticException: / by zero
[See nested exception: java.lang.ArithmeticException: / by zero]
at tv.huan.cms.services.rest.DuMiSynchronizationRetryRest.execute(DuMiSynchronizati onRetryRest.java:34)
at org.quartz.core.JobRunShell.run(JobRunShell.java:216)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549)
Caused by: java.lang.ArithmeticException: / by zero
at tv.huan.cms.services.rest.DuMiSynchronizationRetryRest.execute(DuMiSynchronizat
ionRetryRest.java:30)
... 2 more
В журнале обнаружилось исключение и больше нет подсказок. Как мне достичь своих целей?