ScheduledJobExecutor implements ApplicationContextAware { void execute(Callable<Void> callable, String jobIdentifier) { ScheduledJobLog jobLog; try { callable.call(); var executionTime = LocalDateTime.now(clock); jobLog = new ScheduledJobLog(executionTime, jobIdentifier, ScheduledJobLog.Status.SUCCESS); log.debug(String.format("Successfully executed scheduled job with job identifier '%s'!", jobIdentifier)); } catch (Exception ex) { var executionTime = LocalDateTime.now(clock); jobLog = new ScheduledJobLog(executionTime, jobIdentifier, ScheduledJobLog.Status.FAILURE); log.debug(String.format("Failed to executed scheduled job with job identifier %s!", jobIdentifier), ex); } jobLogRepo.save(jobLog); } @Autowired  ScheduledJobExecutor(ScheduledJobLogRepository jobLogRepo, Clock clock); @Scheduled( initialDelay = 0L, fixedDelay = 120_000L ) void executeJobs(); void registerScheduledJob(@NonNull ScheduledJob scheduledJob); @Override void setApplicationContext(ApplicationContext applicationContext);  }
@Test public void executeJobLogsSuccessWhenJobDoesNotThrowException() { var jobId = "JOB"; var currentTime = LocalDateTime.now(clock); var expectedJobLog = new ScheduledJobLog(currentTime, jobId, ScheduledJobLog.Status.SUCCESS); Callable<Void> callable = () -> { jobMock.execute(); return null; }; scheduledJobExecutor.execute(callable, jobId); verify(jobLogRepoMock).save(jobLogArgumentCaptor.capture()); var actualJobLog = jobLogArgumentCaptor.getValue(); assertThat(actualJobLog).isEqualTo(expectedJobLog); }
@Test public void executeJobLogsFailureWhenJobThrowsException() throws Exception { var jobId = "JOB"; var currentTime = LocalDateTime.now(clock); var expectedJobLog = new ScheduledJobLog(currentTime, jobId, ScheduledJobLog.Status.FAILURE); willThrow(new Exception()).given(jobMock).execute(); Callable<Void> callable = () -> { jobMock.execute(); return null; }; scheduledJobExecutor.execute(callable, jobId); verify(jobLogRepoMock).save(jobLogArgumentCaptor.capture()); var actualJobLog = jobLogArgumentCaptor.getValue(); assertThat(actualJobLog).isEqualTo(expectedJobLog); }