0

按照标题,我有一个使用 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()工作停止时的方法。我该怎么做?

4

1 回答 1

0

您需要使用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.
于 2020-09-08T06:49:57.773 回答