Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring batch stop a job

How can I stop a job in spring batch ? I tried to use this method using the code below:

public class jobListener implements JobExecutionListener{

  @Override
  public void beforeJob(JobExecution jobExecution) {
    jobExecution.setExitStatus(ExitStatus.STOPPED);

  }


  @Override
  public void afterJob(JobExecution jobExecution) {
    // TODO Auto-generated method stub

  }
}

I tried also COMPLETED,FAILED but this method doesn't work and the job continues to execute. Any solution?

like image 385
Alex Avatar asked Oct 18 '22 07:10

Alex


2 Answers

You can use JobOperator along with JobExplorer to stop a job from outside the job (see https://docs.spring.io/spring-batch/reference/html/configureJob.html#JobOperator). The method is stop(long executionId) You would have to use JobExplorer to find the correct executionId to stop.

Also from within a job flow config you can configure a job to stop after a steps execution based on exit status (see https://docs.spring.io/spring-batch/trunk/reference/html/configureStep.html#stopElement).

like image 54
camtastic Avatar answered Oct 22 '22 01:10

camtastic


I assume you want to stop a job by a given name. Here is the code.

String jobName = jobExecution.getJobInstance().getJobName(); // in most cases
DataSource dataSource = ... //@Autowire it in your code
JobOperator jobOperator = ... //@Autowire it in your code
JobExplorerFactoryBean factory = new JobExplorerFactoryBean();
factory.setDataSource(dataSource);
factory.setJdbcOperations(new JdbcTemplate(dataSource));
JobExplorer jobExplorer = factory.getObject();
Set<JobExecution> jobExecutions = jobExplorer.findRunningJobExecutions(jobName);
jobExecutions.forEach(jobExecution -> jobOperator.stop(jobExecution.getId()));
like image 39
naimdjon Avatar answered Oct 22 '22 01:10

naimdjon