下面列出了org.springframework.boot.autoconfigure.batch.JobExecutionEvent#org.springframework.batch.core.repository.JobRestartException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
protected BatchStatus execute(Job job, JobParameters jobParameters)
throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException,
JobParametersInvalidException, JobParametersNotFoundException {
BatchStatus status = BatchStatus.UNKNOWN;
val nextParameters = getNextJobParameters(job, jobParameters);
if (nextParameters != null) {
val execution = jobLauncher.run(job, nextParameters);
if (publisher != null) {
publisher.publishEvent(new JobExecutionEvent(execution));
}
status = execution.getStatus();
}
return status;
}
@DirtiesContext
@Test
public void retryFailedExecutionOnNonRestartableJob() throws Exception {
this.job = this.jobs.get("job").preventRestart()
.start(this.steps.get("step").tasklet(throwingTasklet()).build())
.incrementer(new RunIdIncrementer()).build();
runFailedJob(new JobParameters());
runFailedJob(new JobParameters());
// A failed job that is not restartable does not re-use the job params of
// the last execution, but creates a new job instance when running it again.
assertThat(this.jobExplorer.getJobInstances("job", 0, 100)).hasSize(2);
// try to re-run a failed execution
Executable executable = () -> this.runner.execute(this.job,
new JobParametersBuilder().addLong("run.id", 1L).toJobParameters());
assertThatExceptionOfType(JobRestartException.class)
.isThrownBy(executable::execute)
.withMessage("JobInstance already exists and is not restartable");
}
@Scheduled(cron = "0/10 * * * * ?")
public void runBatchJob()
throws JobExecutionAlreadyRunningException,
JobRestartException, JobInstanceAlreadyCompleteException,
JobParametersInvalidException {
LOGGER.info("start runBatchJob");
if (enabled) {
jobLauncher.run(capitalizeNamesJob, new JobParametersBuilder()
.addDate("date", new Date()).toJobParameters());
}
}
@SuppressWarnings("unchecked")
@Test(expected = SpringBatchLightminApplicationException.class)
public void restartJobExecutionExceptionTest() throws JobParametersInvalidException, JobRestartException,
JobInstanceAlreadyCompleteException, NoSuchJobExecutionException, NoSuchJobException {
final Long jobExecutionId = 10L;
when(this.jobOperator.restart(jobExecutionId)).thenThrow(NoSuchJobExecutionException.class);
this.jobService.restartJobExecution(jobExecutionId);
}
@SuppressWarnings("unchecked")
@Test(expected = SpringBatchLightminApplicationException.class)
public void stopJobExecutionExceptionTest() throws JobParametersInvalidException, JobRestartException,
JobInstanceAlreadyCompleteException, NoSuchJobExecutionException, NoSuchJobException,
JobExecutionNotRunningException {
final Long jobExecutionId = 10L;
when(this.jobOperator.stop(jobExecutionId)).thenThrow(NoSuchJobExecutionException.class);
this.jobService.stopJobExecution(jobExecutionId);
}
protected void startJobs(long year, long month) {
try {
JobParameters jobParameters = new JobParametersBuilder()
.addLong("month", month)
.addLong("year", year)
.toJobParameters();
LOG.info("Running job in jobservice");
jobLauncher.run(employeeJob, jobParameters);
} catch (JobExecutionAlreadyRunningException | JobRestartException
| JobInstanceAlreadyCompleteException | JobParametersInvalidException e) {
LOG.error("Job running failed", e);
//TODO shouldn't we handle this differently?
}
}
@Test
public void whenStarJobs_withGivenYearAndMonth_runJobWithParameters() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
taxCalculatorJobService.runTaxCalculatorJob(new JobStartParams(YEAR, MONTH));
verify(jobLauncherMock).run(any(Job.class), jobParametersArgumentCaptor.capture());
JobParameters jobParameters = jobParametersArgumentCaptor.getValue();
assertThat(jobParameters.getLong("year")).isEqualTo(YEAR);
assertThat(jobParameters.getLong("month")).isEqualTo(MONTH);
}
@ResponseStatus(HttpStatus.CONFLICT)
@ExceptionHandler({ JobExecutionAlreadyRunningException.class, JobExecutionAlreadyCompleteException.class,
JobRestartException.class })
public String handleAlreadyRunningOrComplete(Exception ex) {
LOG.warn("JobExecution already running or complete.", ex);
return ex.getMessage();
}
@Test
public void jobTest() {
JobParametersBuilder builder = new JobParametersBuilder();
try {
JobExecution execution = jobLauncher.run(validJob, builder.toJobParameters());
assertEquals(BatchStatus.COMPLETED, execution.getStatus());
} catch (JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException
| JobParametersInvalidException e) {
e.printStackTrace();
}
}
@Test
public void jobTest() {
try {
JobExecution execution = jobLauncher.run(javaJob, new JobParameters());
assertEquals(BatchStatus.COMPLETED, execution.getStatus());
} catch (JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException
| JobParametersInvalidException e) {
e.printStackTrace();
}
Conference conf = conferenceDao.findById(1L);
log.debug("[email protected]" + conf);
}
@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void paramsAddedToScheduledJobWorks()
throws InterruptedException, JobExecutionAlreadyRunningException, JobRestartException,
JobInstanceAlreadyCompleteException, JobParametersInvalidException, SchedulerException {
Job job1 = job("j1");
Job job2 = job("j2");
jobBuilder.registerJob(job1);
jobBuilder.registerJob(job2);
Map<String, Object> params = new HashMap<String, Object>();
params.put("testParamKey", "testParamValue");
JobParameters expectedParams = JobParamUtil.convertRawToJobParams(params);
JobConfig job1Config = JobConfig.builder().name("j1").properties(params).build();
JobConfig job2Config = JobConfig.builder().name("j2").properties(params).build();
Date now = Date.from(Instant.now().plusMillis(2000));
scheduler.start();
when(jobLauncher.run(job1, expectedParams))
.thenReturn(new JobExecution(new Random().nextLong(), expectedParams));
when(jobLauncher.run(job2, expectedParams))
.thenReturn(new JobExecution(new Random().nextLong(), expectedParams));
scheduler.schedule(job1Config, now);
scheduler.schedule(job2Config, TRIGGER_EVERY_SECOND);
ArgumentCaptor<Job> jobCaptor = ArgumentCaptor.forClass(Job.class);
ArgumentCaptor<JobParameters> jobParamCaptor = ArgumentCaptor.forClass(JobParameters.class);
verify(jobLauncher, timeout(8000).times(2)).run(jobCaptor.capture(), jobParamCaptor.capture());
List<JobParameters> paramsListAfterCall = jobParamCaptor.getAllValues();
Assertions.assertEquals(paramsListAfterCall.size(), 2);
for (JobParameters jobParams : paramsListAfterCall) {
Assertions.assertEquals(jobParams.getString("testParamKey"), "testParamValue");
}
scheduler.pause();
}
private void startNextInstance() throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException,
JobParametersInvalidException, JobRestartException, JobParametersNotFoundException, NoSuchJobException {
jobOperator.startNextInstance(job.getName());
}
protected void execute(Job job, JobParameters jobParameters)
throws JobExecutionAlreadyRunningException, JobRestartException,
JobInstanceAlreadyCompleteException, JobParametersInvalidException {
String jobName = job.getName();
JobParameters parameters = jobParameters;
boolean jobInstanceExists = this.taskJobRepository.isJobInstanceExists(jobName,
parameters);
if (jobInstanceExists) {
JobExecution lastJobExecution = this.taskJobRepository
.getLastJobExecution(jobName, jobParameters);
if (lastJobExecution != null && isStoppedOrFailed(lastJobExecution)
&& job.isRestartable()) {
// Retry a failed or stopped execution with previous parameters
JobParameters previousParameters = lastJobExecution.getJobParameters();
/*
* remove Non-identifying parameters from the previous execution's
* parameters since there is no way to remove them programmatically. If
* they are required (or need to be modified) on a restart, they need to
* be (re)specified.
*/
JobParameters previousIdentifyingParameters = removeNonIdentifying(
previousParameters);
// merge additional parameters with previous ones (overriding those with
// the same key)
parameters = merge(previousIdentifyingParameters, jobParameters);
}
}
else {
JobParametersIncrementer incrementer = job.getJobParametersIncrementer();
if (incrementer != null) {
JobParameters nextParameters = new JobParametersBuilder(jobParameters,
this.taskJobExplorer).getNextJobParameters(job).toJobParameters();
parameters = merge(nextParameters, jobParameters);
}
}
JobExecution execution = this.taskJobLauncher.run(job, parameters);
if (this.taskApplicationEventPublisher != null) {
this.taskApplicationEventPublisher
.publishEvent(new JobExecutionEvent(execution));
}
this.jobExecutionList.add(execution);
if (execution.getStatus().equals(BatchStatus.FAILED)) {
throwJobFailedException(Collections.singletonList(execution));
}
}
/**
* Launch a job with the parameters provided. If an instance with the parameters provided
* has already failed (and is not abandoned) it will be restarted.
*
* @param jobName the job name
* @param params the {@link JobParameters}
* @return the resulting {@link JobExecution} if successful
*
* @throws NoSuchJobException thrown if job specified does not exist
* @throws JobExecutionAlreadyRunningException thrown if job is already executing
* @throws JobRestartException thrown if job failed to restart
* @throws JobInstanceAlreadyCompleteException thrown if job was already complete
* @throws JobParametersInvalidException thrown if job parameters are invalid
*/
JobExecution launch(String jobName, JobParameters params) throws NoSuchJobException,
JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException,
JobParametersInvalidException;
/**
* Launch a job with the parameters provided.
*
* @param jobExecutionId the job execution to restart
* @return the resulting {@link JobExecution} if successful
*
* @throws NoSuchJobExecutionException thrown if job execution specified does not exist
* @throws NoSuchJobException thrown if job specified does not exist
* @throws JobExecutionAlreadyRunningException thrown if job is already executing
* @throws JobRestartException thrown if job failed to restart
* @throws JobInstanceAlreadyCompleteException thrown if job was already complete
* @throws JobParametersInvalidException thrown if job parameters are invalid
*/
JobExecution restart(Long jobExecutionId) throws NoSuchJobExecutionException, JobExecutionAlreadyRunningException,
JobRestartException, JobInstanceAlreadyCompleteException, NoSuchJobException, JobParametersInvalidException;
/**
* Launch a job with the parameters provided. JSR-352 supports restarting of jobs with a
* new set of parameters. This method exposes this functionality
*
* @param jobExecutionId the job execution to restart
* @param params the job parameters to use in the restart
* @return the resulting {@link JobExecution} if successful
*
* @throws NoSuchJobExecutionException thrown if job execution specified does not exist
* @throws NoSuchJobException thrown if job specified does not exist
* @throws JobExecutionAlreadyRunningException thrown if job is already executing
* @throws JobRestartException thrown if job failed to restart
* @throws JobInstanceAlreadyCompleteException thrown if job was already complete
* @throws JobParametersInvalidException thrown if job parameters are invalid
*/
JobExecution restart(Long jobExecutionId, JobParameters params)
throws NoSuchJobExecutionException, JobExecutionAlreadyRunningException,
JobRestartException, JobInstanceAlreadyCompleteException, NoSuchJobException, JobParametersInvalidException;