如何轮询正在执行的作业的 BatchStatus?

How to poll BatchStatus for an executing job?

我有一个批处理作业,必须对项目列表重复。所以我有一个 "parent" 作业,它使用 batchlet 步骤加载列表并为列表中的每个 id 启动一个 child 作业。 每个 child 作业都使用 JobOperator 和参数使用 Properties class 启动,这按预期工作正常。

我必须检索批处理状态并等待 child 作业完成,以便遍历列表。我正在尝试使用 JobExecution class 获取批处理状态或退出状态,但是 JobExecution 没有检索批处理状态对于 child 工作。

相反,我总是看到 STARTED 的批处理状态,即使在 child 作业完成后也是如此。

我的代码如下:

for (int i = 1; i <= rsList; i++) {
            long execId = jobOperator.start("gah-history-chunk-archive-job",jobParamProperties);
            JobInstance jobInstance = jobOperator.getJobInstance(execId);
            JobExecution jobExecution = jobOperator.getJobExecution(execId);
            logger.info("Instance id: "+jobInstance.getInstanceId());
            while(!jobExecution.getBatchStatus().toString().equals("COMPLETED") || !jobExecution.getBatchStatus().toString().equals("FAILED")) {
                //Both batch status and exit status giving the status of this batchlet, not giving the status of gah-history-chunk-archive-job
logger.info("Batch status is: "+jobExecution.getBatchStatus() +" Thread is sleeping for 5 seconds");
                logger.info("Exit status:"+jobExecution.getExitStatus());

                Thread.sleep(300);
            }
        }

我想知道如何检索从 batchlet 启动的 child 作业的批处理或退出状态。为什么我继续看到 STARTED 的 BatchStatus?

JobExecution 指向父作业,即使它是用子作业执行 ID 设置的。不确定批处理为什么会这样。

JobExecution jobExecution = jobOperator.getJobExecution(execId);
jobExecution.getBatchStatus(); //Parent job status

但是如果我们使用 BatchRuntime class,我们可以获得相应的作业、批处理状态。这有助于我获取子作业状态并可以循环到下一个批次启动。

//Returns the child job status as expected
BatchRuntime.getJobOperator().getJobExecution(execId).getBatchStatus();

要"poll" JobExecution 的状态,您应该在每次检查其状态时从 JobOperator 获取一个新实例。因此,将 JobExecution 放在 内 while-loop,而不是放在外面。

所以应该更像,例如:

do {
  Thread.sleep(300);

  // log or whatever

  BatchStatus status = jobOperator.getJobExecution(execId).getBatchStatus();

}  while(status != BatchStatus.COMPLETED && status != BatchStatus.FAILED) ;

这有点棘手,因为这里的行为没有被规范标准化。
因为规范允许多种作业存储库实现(例如数据库、简单的 in-memory 映射、其他...),它不需要 "cached" JobExecution 的特定行为,您可以发现它 "works" 有时与您的原始代码相同。

我不认为您实际看到的是返回的 "parent" 对象实例;我怀疑您可能只是因为没有看到您期望的内容而感到困惑。

无论如何,为了让您的代码更具可移植性,请在每次状态检查时获取 JobExecution

我建议轮询作业的 Exitstatus 而不是 BatchStatus 本身:

for (int i = 1; i <= rsList; i++) {
    long execId = jobOperator.start("gah-history-chunk-archive-job",jobParamProperties);
    JobInstance jobInstance = jobOperator.getJobInstance(execId);
    JobExecution jobExecution = jobOperator.getJobExecution(execId);
    logger.info("Instance id: "+jobInstance.getInstanceId());
    while(jobExecution.getExitStatus() == null) {
        //do your logging etc.   
        Thread.sleep(300);
    }
}