Spring batch stop a job

元气小坏坏 提交于 2020-02-24 03:58:04

问题


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?


回答1:


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).




回答2:


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


来源:https://stackoverflow.com/questions/45883746/spring-batch-stop-a-job

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!