问题描述
跟随标题,我有一个使用spring batch在后端运行的服务。
我的服务:
@Service
publlic class TestBatch {
public void testDelay(String jobID) {
// Todo Auto-generated method stub
try {
for(int i=0; i< 1000; i++) {
Thread.sleep(1000);
System.out.println(jobID + " is running");
}
} catch (InterruptedException e) {
// Todo Auto-generated catch block
e.printstacktrace();
}
}
}
我的小任务:
public class Testtasklet implement tasklet {
@Resource
private TestBatch testBatch ;
@Override
public RepeatStatus execute(StepContribution contribution,ChunkContext chunkContext) throws Exception {
testBatch.testDelay("Test01"); // Param to show in cololog
return RepeatStatus.FINISHED;
}
}
我正在尝试停止工作:
@Service
public class JobService {
@Autowired
private SimpleJobOperator simpleJobOperator;
@Autowired
private JobExplorer jobs;
public void stopJob(String jobid) {
simpleJobOperator.stop(jobid);// Using job operator
JobExecution jobExecution = jobs.getJobExecution(jobid); // Using job execution
jobExecution.stop();
}
}
作业已停止,但在我的控制台中仍输出文本:
Test01 is running
Test01 is running
Test01 is running
...
我不知道如何停止TestBatch
-作业停止时的方法testDelay()
。我该怎么办?
解决方法
您需要使用StoppableTasklet而不是Tasklet
。当要求通过StoppableTasklet#stop
停止作业时,Spring Batch将调用JobOperator
。
但是,由您决定确保代码正确停止,这是Javadoc的摘录:
It is up to each implementation as to how the stop will behave.
The only guarantee provided by the framework is that a call to JobOperator.stop(long)
will attempt to call the stop method on any currently running StoppableTasklet.