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?
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);
}
}
}
Basically, you can do as follows:
Configure a JobExplorer
factory bean in your application context:
Configure a JobOperator
bean in your applictaion context
Query the jobExplorer for distinct job names: jobExplorer.getJobNames()
For each job from step (3), query the jobExplorer for unfinished jobs:
jobExplorer.findRunningJobExecutions(String jobName)
For each JobExecution
from step (4) invoke:jobOperator.restart(jobExecution.getJobId())
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With