Search code examples
javaspring-batchrestart

Spring Batch: How to find out if job is restarted


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.


Solution

  • 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