Spring Batch: How to find out if job is restarted

10,772

Solution 1

Define a JobExplorer bean with required properties

<bean id="jobExplorer"
class="org.springframework.batch.core.explore.support.JobExplorerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="lobHandler" ref="lobHandler"/>
</bean>

Query it with your jobName

List<JobInstance> jobInstances= jobExplorer.getJobInstances(jobName);

for (JobInstance jobInstance : jobInstances) {
    List<JobExecution> jobExecutions = jobExplorer.getJobExecutions(jobInstance);
    for (JobExecution jobExecution : jobExecutions) {
        if (jobExecution.getExitStatus().equals(ExitStatus.COMPLETED)) {
        //You found a completed job, possible candidate for a restart
        //You may check if the job is restarted comparing jobParameters
        JobParameters jobParameters = jobInstance.getParameters();
        //Check your running job if it has the same jobParameters 
        }
     }
}

Did not compile this but I hope it gives an idea

Solution 2

Another way using jobExplorer is execute the following command:

jobExplorer.getJobExecutions(jobExplorer.getJobInstance(currentJobExecution.getJobInstance().getId())).size() > 1;

This statement verifies if another execution of the the same job (same id) exists. In environments with minimum control, does not exist possibility that the other execution be not a failed or stopped execution.

Share:
10,772
maxstreifeneder
Author by

maxstreifeneder

Updated on June 04, 2022

Comments

  • maxstreifeneder
    maxstreifeneder almost 2 years

    Is there any possibility to find out, If a job is restarted in Spring Batch?

    We do provide some Tasklets without restart-support from spring-batch and has to implement our own proceeding, if job is restarted.

    Can't find any possibility in JobRepository, JobOperator, JobExplorer, etc.

  • maxstreifeneder
    maxstreifeneder almost 12 years
    would prefer a other aproach, without accessing the database directly
  • maxstreifeneder
    maxstreifeneder almost 12 years
    it's a quietly cool approach in my opinion. By the way: Am I right in thinking that only uncompleted JobInstances can be restarted? thanks for your help!