如何在春季批处理中停止服务

问题描述

跟随标题我有一个使用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.

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...