我已经成功地使用此方法暂停了之前的工作。
public class FirstListener implements StepExecutionListener {
@Override
public void beforeStep(StepExecution stepExecution) {
boolean shouldRun = shouldJobRun();
if (!shouldRun) {
// listeners will still work, but any other step logic (reader, processor, writer) will not happen
stepExecution.setTerminateOnly();
stepExecution.setExitStatus(new ExitStatus("STOPPED", "Job should not be run right now."));
LOGGER.warn(duplicate_message);
}
}
代码是为了简洁/清晰而修剪,但这是要点。调用stepExecution.setTerminateOnly()
和stepExecution.setExitStatus()
足以让Spring Batch暂停作业而不执行任何后续步骤。状态在BATCH_JOB_EXECUTION
表
EXIT_MESSAGE STATUS
org.springframework.batch.core.JobInterruptedException STOPPED
但是,afterStep
方法中的相同方法会被翻转并无法识别。状态被记录为COMPLETED,所有后续步骤都以他们的快乐方式进行(最终以他们自己的可怕方式失败,因为afterStep中的故障检测正在检测故障,因此他们不必这样做。)
public class SecondListener implements StepExecutionListener {
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
if (stepExecution.getExitStatus().getExitCode().equals(ExitStatus.STOPPED.getExitCode())) {
return stepExecution.getExitStatus();
}
if (everythingIsOkay()) {
return stepExecution.getExitStatus();
}
String failureMessage = "Something bad happened.";
LOGGER.error(failureMessage);
ExitStatus exitStatus = new ExitStatus(ExitStatus.FAILED.getExitCode(), failureMessage);
stepExecution.setExitStatus(exitStatus);
stepExecution.setTerminateOnly();
return exitStatus;
}
这是我能想到的唯一皱纹:两个听众都使用复合听众处于相同的步骤。
@Bean(name = "org.springframework.batch.core.StepExecutionListener-compositeListener")
@StepScope
public StepExecutionListener compositeListener() {
CompositeStepExecutionListener listener = new CompositeStepExecutionListener();
List<StepExecutionListener> listeners = Lists.newArrayList(secondListener());
if (jobShouldHaveFirstListener()) {
listeners.add(0, firstListener()); // prepend; delegates are called in order
}
listener.setListeners(listeners.toArray());
return listener;
}
public Step firstStep() {
return stepBuilderFactory.get("firstStep")
.listener(compositeListener)
// Small batch size for frequency capping, which happens in the writer, before analytics get written
.<Recipient, Recipient>chunk(500)
.reader(rawRecipientInputFileItemReader)
.processor(recipientItemProcessor)
.writer(recipientWriter)
.throttleLimit(2)
.build();
}
@Bean(name = "org.springframework.batch.core.Job-delivery")
public Job deliveryJob() {
return jobs.get("delivery")
.preventRestart()
.start(firstStep)
.next(deliveryStep)
.next(handleSentStep)
.listener(failedCleanupListener)
.build();
}
我能做些什么来让这个执行正确停止吗?
答案 0 :(得分:1)
经过大量实验,我发现以下流程定义将允许从StepListener正确暂停作业,而不会在第一步之后执行步骤。
return jobs.get("delivery")
.preventRestart()
.listener(failedCleanupListener)
.flow(firstStep)
.next(deliveryStep)
.next(handleSentStep)
.end()
.build();
关键区别在于将start()
更改为flow()
并将FlowBuilder.end()
方法调用添加到构建器链的末尾。从.start
方法返回的SimpleJobBuilder
类不会公开类似的end()
方法。
我不知道为什么这会在作业执行的内部产生如此大的差别,我很乐意向某些人提供一些观点,这些观点可以说明 实际的差异是什么为什么使用SimpleJobBuilder忽略步骤执行状态代码。但是我发现了一些有效的东西,这就是现在最重要的东西。