Search code examples
javaspring-bootspring-batch

How to get the start or end date of the last execution of a Spring Batch job that has a completed status?


I am writing a Spring Batch process (Spring boot 2.x.x). The job selects some rows from a table based on the last update date -

(select * from tablename where last_upd_dt >= :lastruntime).

The :lastruntime is the date of the last (successfully) completed run of the job. I am trying to grab this date from the beforeJob method in the Listener class using JobListener/JobExecutionListener.

Is there a way to leverage the classes Spring Batch framework offers? Else I will have to write and retrieve this info from another table.


Solution

  • I was able to use the JobExplorer API.

    private Date fetchPreviousJobCompletetionDate() {
        Date previousJobCompleteDate = null;
        try {
            Integer jobInstanceCount = jobExplorer.getJobInstanceCount("myjob");
            List<JobInstance> jobInstances = jobExplorer.getJobInstances("myjob", 0, jobInstanceCount);
            List<JobExecution> jobExecutions = jobInstances.stream().map(jobExplorer::getJobExecutions)
                    .flatMap(List<JobExecution>::stream)
                    .filter(param -> param.getExitStatus().equals(ExitStatus.COMPLETED)).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(jobExecutions)) {
                Optional<JobExecution> jobExecutionOptional = jobExecutions.stream().sorted((JobExecution execution1, JobExecution execution2) -> execution2.getStartTime()
                        .compareTo(execution1.getStartTime())).findFirst();
                if (jobExecutionOptional.isPresent()) {
                    previousJobCompleteDate = jobExecutionOptional.get().getStartTime();
                }
            }
        } catch (NoSuchJobException exception) {
            log.error("Exception occurred {}", exception.getMessage());
        }
        return previousJobCompleteDate;
    }