Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Batch after JVM crash

How to restart Jobs after a JVM crash?

I was running a lot of Jobs implemented in Spring Batch framework, when my JVM crashed or the system failed. How can I restart these Jobs after failure?

like image 969
Yosefarr Avatar asked Mar 17 '13 13:03

Yosefarr


2 Answers

You need to mark the "running" jobs as failed before restarting them, like this:

List<String> jobs = jobExplorer.getJobNames();
for (String job : jobs) {
    Set<JobExecution> runningJobs = jobExplorer.findRunningJobExecutions(job);

    for (JobExecution runningJob : runningJobs) {
        try {
            runningJob.setStatus(BatchStatus.FAILED);
            runningJob.setEndTime(new Date());
            jobRepository.update(runningJob);
            jobOperator.restart(runningJob.getId());
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
    }
}
like image 190
robvelor Avatar answered Sep 21 '22 17:09

robvelor


Basically, you can do as follows:

  1. Configure a JobExplorer factory bean in your application context:

  2. Configure a JobOperator bean in your applictaion context

  3. Query the jobExplorer for distinct job names: jobExplorer.getJobNames()

  4. For each job from step (3), query the jobExplorer for unfinished jobs: jobExplorer.findRunningJobExecutions(String jobName)

  5. For each JobExecution from step (4) invoke:jobOperator.restart(jobExecution.getJobId())

  6. Make sure to call this procedure during boot sequence, before any other job is launched

Technically it is possible to merge steps 3+4 for something like findRunningJobExecutions() by overriding JobExecutionDao, but the current API doesn't support it.

For help in aforementioned Spring bean configuration, consult the reference documentation

like image 30
Ori Dar Avatar answered Sep 19 '22 17:09

Ori Dar