Spring batch restrict single instance of job only

spring batch disable metadata tables
spring batch prevent concurrent jobs
a job execution for this job is already running job instance id=0, version=0
spring batch run multiple jobs sequentially
spring batch job running twice
spring boot batch multiple jobs example
how to stop spring batch job programmatically
spring batch batchconfigurer example

I have one spring batch job which can be kicked of by rest URL. I want to make sure only one job instance is allowed to run. and if another instance already running then don't start another. even if the parameters are different.

I searched and found nothing out of box solution. thinking of extending SimpleJobLauncher. to check if any instance of the job running or not.

You could try to intercept the job execution, implementing the JobExecutionListener interface:

public class MyJobExecutionListener extends JobExecutionListener {

    //active JobExecution, used as a lock.
    private JobExecution _active;

    public void beforeJob(JobExecution jobExecution) {
        //create a lock
        synchronized(jobExecution) {
            if(_active!=null && _active.isRunning()) {
                jobExecution.stop();
            } else {
                _active=jobExecution;
            }
        }
    }

    public void afterJob(JobExecution jobExecution) {
          //release the lock
          synchronized(jobExecution) {
              if(jobExecution==_active) {
                _active=null; 
              }
          }
    }
}

And then, inject to the Job definition:

<job id="myJobConfig">
    <listeners>
        <listener ref="myListener"/>
    </listeners>
</job>

java - Spring batch restrict single instance of job only, I have one spring batch job which can be kicked of by rest URL. I want to make sure only one job instance is allowed to run. and if another instance already  Spring Batch – How many jobs? For a description of the Spring Batch framework, take a look here. When creating a batch job, the requirement is usually for a single job to process a number of records. However, it is often useful to have a number of variations of the job: To process all the records; To process a selected list of records

I solved this by creating an JobExecutionListner and with the help of JobExplorer I checked if any other instance is running if running then stop current job.I created listener so that it can be plugged in to any job that requires this kind of scenario.

Set<JobExecution> jobExecutions = ((SimpleJobExplorer) jobExplorer.getObject()).findRunningJobExecutions(jobExecution.getJobInstance().getJobName());
            if(jobExecutions.size()>1){
                Long currentTime = (new Date()).getTime();
                for(JobExecution execution : jobExecutions ){
                    if(execution.getJobInstance().getId().compareTo(jobExecution.getJobInstance().getId())!=0 && (currentTime - execution.getStartTime().getTime()) <lockOverideTime){
                        jobExecution.stop();
                        throw new IllegalStateException("Another instance of the job running job name : " +jobExecution.getJobInstance().getJobName() );

                    }
                }

            }

Running only one Job Instance at , an occasional use case in Spring Batch is the need to have only one instance of a Job running at any given time. this might be due to  Working with Spring Batch 2.2.0.RELEASE, and launches the job with Spring Scheduler.

Or, in response to REST URL, check using JobExplorer if your job is running using job's specifics business rules

Spring batch restrict single instance of job only, I have one spring batch job which can be kicked of by rest URL. I want to make sure only one job instance is allowed to run. and if another instance already  Spring Batch automates this basic batch iteration, providing the capability to process similar transactions as a set, typically in an offline environment without any user interaction. Batch jobs are part of most IT projects and Spring Batch is the only open source framework that provides a robust, enterprise-scale solution. Business Scenarios

I think a simple method like the following might do the trick:

@Autowire
private JobExplorer jobExplorer;

private boolean isJobRunning(Job job) {
    Set<JobExecution> jobExecutions = jobExplorer.findRunningJobExecutions(job.getName());
    return !jobExecutions.isEmpty();
}

Then, prior to executing your job make the check:

private void executeJob(Job job, @Nonnull JobParameters params) {
    if (isJobRunning(job)) {
        return;
    }

    try {
        jobLauncher.run(job, params);
    } catch (JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException | JobParametersInvalidException e) {
        log.error("could not run job " + jobIdentifier, e);
    }
}

Spring Batch : A job instance already exists and is complete for , The batch job is running successful in the first time only, when it launches the second time (after 10 seconds) it prompts following error messages. A shell script to start Java is generally described to start a Job defined on Spring Batch, along with starting a Java process. When CommandLineJobRunner offered by Spring Batch is used, Job on Spring Batch defined by the user can be easily started.

Chapter 10. Controlling execution, This chapter covers mastering job execution with Spring Batch. For linear flows​, only the next attribute in the step element needs to be set and must Jl job instance a ntd nj rvg mcck oesscrp—uebsaec bpv eedddebm Sgripn Yrzga jn c wgo  A Job is an entity that encapsulates an entire batch process. As is common with other Spring projects, a Job is wired together with either an XML configuration file or Java-based configuration. This configuration may be referred to as the "job configuration". However, Job is just the top of an overall hierarchy, as shown in the following diagram:

Spring Batch - Reference Documentation, Batch jobs are part of most IT projects, and Spring Batch is the only open source Split: A program that reads a single input file and writes each record to one of to the batch/extract application in order to restrict its processing to only its portion. Assigned to a batch instance by a portion of the value (such as 0000-0999,  Many batch processing problems can be solved with single threaded, single process jobs, so it is always a good idea to properly check if that meets your needs before thinking about more complex implementations. Measure the performance of a realistic job and see if the simplest implementation meets your needs first.

Chapter 4. Configuring and Executing A Job, Spring Batch provides an implementation that serves just this purpose: JobInstance , JobExecution , and StepExecution each have unique IDs, and the processes are trying to launch the same job at the same time, only one will succeed. Starting Salary is $72,931 a Year. No Experience Necessary. Start Now! Starting Salary is $72,391 a Year. No Experience Necessary. Start Now!

Comments
  • Thanks for this solution I need to try this and will update if it works for me and meet my all requirements.
  • What happens if you shut down the server while a job is running? If you restart the server it will be still marked as started but is actually broken. Wouldn't this solution then not start an instance of this job anymore?
  • findRunningJobExecutions() basically returns job executions without an endTime. If you have older executions that didn't finish correctly, this won't work.