按照标题,我有一个使用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
。当作业通过JobOperator
被请求停止时,Spring Batch将调用StoppableTasklet#stop
。
然而,这取决于您是否确保您的代码正确停止,以下是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.