如何获取具有已完成状态的 Spring 批处理作业的最后一次执行的开始或结束日期?

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

我正在写一个Spring批处理(Spring启动2.x.x)。该作业根据上次更新日期 -

从 table 中选择一些行
(select * from tablename where last_upd_dt >= :lastruntime).

:last运行时间是最后一次(成功)完成 运行 作业的日期。我正在尝试使用 JobListener/JobExecutionListener.

从 Listener class 的 beforeJob 方法中获取此日期

有没有办法利用 classes Spring 批处理框架提供的服务?否则我将不得不从另一个 table.

写入和检索此信息

可以使用JobExplorerAPI。它允许您获取作业实例的作业执行。一旦你得到它,你可以根据需要过滤结果并从 JobExecution 对象中获取 start/end 日期。

我能够使用 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;
}