Home > Mobile >  How to get the start or end date of the last execution of a Spring Batch job that has a completed st
How to get the start or end date of the last execution of a Spring Batch job that has a completed st

Time:11-27

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.

CodePudding user response:

You can use the JobExplorer API. It allows you to get the job executions of your job instance. Once you get that, you can filter the result as needed and get the start/end date from the JobExecution object.

CodePudding user response:

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;
}
  • Related