简体   繁体   中英

How to stop service in spring batch

Follow the title, i have a service running in backend using spring batch.
My service:

@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();
        }
    }
}

My tasklet:

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;
    }
}

I'm try to stop job:

@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();
    }
}

Job is stop, but in my console still output text:

Test01 is running
Test01 is running
Test01 is running
...

I don't know how to stop TestBatch - method testDelay() when job stop. How can i do it?

You need to use StoppableTasklet and not Tasklet . Spring Batch will call StoppableTasklet#stop when the job is requested to stop through the JobOperator .

However, it is up to you to make sure your code stops correctly, here is an excerpt from the 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM