Example usage for org.springframework.batch.core JobExecution getStartTime

List of usage examples for org.springframework.batch.core JobExecution getStartTime

Introduction

In this page you can find the example usage for org.springframework.batch.core JobExecution getStartTime.

Prototype

public Date getStartTime() 

Source Link

Usage

From source file:org.trpr.platform.batch.impl.spring.admin.repository.MapJobExecutionDao.java

/**
 * Returns a copy of {@link JobExecution}, by adding new Objects for every field(no references are passed)
 * //  ww  w. j a  va  2s  .  c om
 * @param original JobExecution to be copied
 * @return JobExecution copy
 */
private static JobExecution copy(JobExecution original) {
    JobInstance jobInstance = original.getJobInstance();
    JobExecution copy;
    if (jobInstance == null) {
        copy = new JobExecution(original.getId());
    }
    copy = new JobExecution(jobInstance, original.getId());
    if (original.getStartTime() != null) {
        copy.setStartTime((Date) original.getStartTime().clone());
    }
    if (original.getEndTime() != null) {
        copy.setEndTime((Date) original.getEndTime().clone());
    }
    if (original.getStatus() != null) {
        copy.setStatus(BatchStatus.valueOf(original.getStatus().name()));
    }
    if (original.getExitStatus() != null) {
        copy.setExitStatus(new ExitStatus(original.getExitStatus().getExitCode(),
                original.getExitStatus().getExitDescription()));
    }
    if (original.getCreateTime() != null) {
        copy.setCreateTime((Date) original.getCreateTime().clone());
    }
    if (original.getLastUpdated() != null) {
        copy.setLastUpdated((Date) original.getLastUpdated().clone());
    }
    copy.setVersion(original.getVersion());
    return copy;
}

From source file:admin.history.JobExecutionHistory.java

public void append(JobExecution jobExecution) {
    if (jobExecution.getEndTime() == null) {
        // ignore unfinished executions
        return;/*w  w  w . ja  va  2 s  .co m*/
    }
    Date startTime = jobExecution.getStartTime();
    Date endTime = jobExecution.getEndTime();
    long time = endTime.getTime() - startTime.getTime();
    duration.append(time);
}

From source file:org.appverse.web.framework.backend.batch.services.business.impl.live.JobRunnerServiceImpl.java

private boolean skipExecution(String jobName, int postExecutionSleepTime) {
    Date startDate = null;/*from w w w . j  ava2s  .c o  m*/
    List<JobInstance> jobInstances = jobExplorer.getJobInstances(jobName, 0, 1);

    if (CollectionUtils.isNotEmpty(jobInstances)) {
        // This will retrieve the latest job execution:
        List<JobExecution> jobExecutions = jobExplorer.getJobExecutions(jobInstances.get(0));

        if (CollectionUtils.isNotEmpty(jobExecutions)) {
            JobExecution jobExecution = jobExecutions.get(0);
            startDate = jobExecution.getStartTime();
            Long lastExecutionOffsetAsString = (Long) jobExecution.getExecutionContext().get("offset");
            long lastExecutionOffset = 0;
            if (lastExecutionOffsetAsString != null) {
                lastExecutionOffset = lastExecutionOffsetAsString.longValue();
            } else {
                lastExecutionOffset = TimeZone.getDefault().getOffset(new Date().getTime());
            }
            Date currentDate = new Date();
            long offset = TimeZone.getDefault().getOffset(new Date().getTime());

            if (startDate != null && currentDate.getTime() - offset
                    - (startDate.getTime() - lastExecutionOffset) < postExecutionSleepTime * 1000) {
                logger.debug("Current date offset " + offset);
                logger.debug("Current date with offset " + (currentDate.getTime() - offset));
                logger.debug("Last execution date offset " + lastExecutionOffset);
                logger.debug("Last execution date with offset " + (startDate.getTime() - lastExecutionOffset));
                logger.debug("Current date with offset - start date with offset "
                        + (currentDate.getTime() - offset - (startDate.getTime() - lastExecutionOffset)));
                logger.info("Batch executed "
                        + (currentDate.getTime() - offset - (startDate.getTime() - lastExecutionOffset)) / 60000
                        + " minutes before");
                logger.info("Batch run skipped ");
                return true;
            }
        }
    }
    logger.info("Batch run started ");
    return false;
}

From source file:de.codecentric.batch.metrics.MetricsListener.java

@Override
public void afterJob(JobExecution jobExecution) {
    long jobDuration = jobExecution.getEndTime().getTime() - jobExecution.getStartTime().getTime();
    gaugeService.submit(TIMER_PREFIX + jobExecution.getJobInstance().getJobName() + ".duration", jobDuration);
    // What the f*** is that Thread.sleep doing here? ;-)
    // Metrics are written asynchronously to Spring Boot's repository. In our tests we experienced
    // that sometimes batch execution was so fast that this listener couldn't export the metrics
    // because they hadn't been written. It all happened in the same millisecond. So we added
    // a Thread.sleep of 100 milliseconds which gives us enough safety and doesn't hurt anyone.
    try {//from   w  w  w  .j a v a  2  s . c om
        Thread.sleep(100);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    // Export Metrics to Console or Remote Systems
    LOGGER.info(metricsOutputFormatter.format(exportBatchRichGauges(), exportBatchMetrics()));
    // Codahale
    if (exporters != null) {
        for (Exporter exporter : exporters) {
            if (exporter != null) {
                LOGGER.info("Exporting Metrics with " + exporter.getClass().getName());
                exporter.export();
            }
        }
    }
}

From source file:admin.jmx.SimpleJobExecutionMetrics.java

public Date getLatestStartTime() {
    JobExecution jobExecution = getLatestJobExecution(jobName);
    return jobExecution == null ? null : jobExecution.getStartTime();
}

From source file:org.wallride.service.PostService.java

@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void updatePostViews() {
    LocalDateTime now = LocalDateTime.now();
    Set<JobExecution> jobExecutions = jobExplorer.findRunningJobExecutions("updatePostViewsJob");
    for (JobExecution jobExecution : jobExecutions) {
        LocalDateTime startTime = LocalDateTime.ofInstant(jobExecution.getStartTime().toInstant(),
                ZoneId.systemDefault());
        Duration d = Duration.between(now, startTime);
        if (Math.abs(d.toMinutes()) == 0) {
            logger.info("Skip processing because the job is running.");
            return;
        }//  w w  w .  j ava 2s  .  c  o  m
    }

    JobParameters params = new JobParametersBuilder()
            .addDate("now", Date.from(now.atZone(ZoneId.systemDefault()).toInstant())).toJobParameters();
    try {
        jobLauncher.run(updatePostViewsJob, params);
    } catch (Exception e) {
        throw new ServiceException(e);
    }
}

From source file:de.codecentric.batch.listener.ProtocolListener.java

public void afterJob(JobExecution jobExecution) {
    StringBuilder protocol = new StringBuilder();
    protocol.append("\n");
    protocol.append(createFilledLine('*'));
    protocol.append(createFilledLine('-'));
    protocol.append("Protocol for " + jobExecution.getJobInstance().getJobName() + " \n");
    protocol.append("  Started:      " + jobExecution.getStartTime() + "\n");
    protocol.append("  Finished:     " + jobExecution.getEndTime() + "\n");
    protocol.append("  Exit-Code:    " + jobExecution.getExitStatus().getExitCode() + "\n");
    protocol.append("  Exit-Descr:   " + jobExecution.getExitStatus().getExitDescription() + "\n");
    protocol.append("  Status:       " + jobExecution.getStatus() + "\n");
    protocol.append("  Content of Job-ExecutionContext:\n");
    for (Entry<String, Object> entry : jobExecution.getExecutionContext().entrySet()) {
        protocol.append("  " + entry.getKey() + "=" + entry.getValue() + "\n");
    }//from   ww w .ja  v a  2 s  .  c  o  m
    protocol.append("  Job-Parameter: \n");
    JobParameters jp = jobExecution.getJobParameters();
    for (Iterator<Entry<String, JobParameter>> iter = jp.getParameters().entrySet().iterator(); iter
            .hasNext();) {
        Entry<String, JobParameter> entry = iter.next();
        protocol.append("  " + entry.getKey() + "=" + entry.getValue() + "\n");
    }
    protocol.append(createFilledLine('-'));
    for (StepExecution stepExecution : jobExecution.getStepExecutions()) {
        protocol.append("Step " + stepExecution.getStepName() + " \n");
        protocol.append("  ReadCount:    " + stepExecution.getReadCount() + "\n");
        protocol.append("  WriteCount:   " + stepExecution.getWriteCount() + "\n");
        protocol.append("  Commits:      " + stepExecution.getCommitCount() + "\n");
        protocol.append("  SkipCount:    " + stepExecution.getSkipCount() + "\n");
        protocol.append("  Rollbacks:    " + stepExecution.getRollbackCount() + "\n");
        protocol.append("  Filter:       " + stepExecution.getFilterCount() + "\n");
        protocol.append("  Content of Step-ExecutionContext:\n");
        for (Entry<String, Object> entry : stepExecution.getExecutionContext().entrySet()) {
            protocol.append("  " + entry.getKey() + "=" + entry.getValue() + "\n");
        }
        protocol.append(createFilledLine('-'));
    }
    protocol.append(createFilledLine('*'));
    LOGGER.info(protocol.toString());
}

From source file:com.github.jrrdev.mantisbtsync.core.jobs.issues.tasklets.IssuesLastRunExtractorTasklet.java

/**
 * {@inheritDoc}/*from w  w  w  .ja  va 2 s  .  co m*/
 * @see org.springframework.batch.core.step.tasklet.Tasklet#execute(org.springframework.batch.core.StepContribution, org.springframework.batch.core.scope.context.ChunkContext)
 */
@Override
public RepeatStatus execute(final StepContribution contribution, final ChunkContext chunkContext)
        throws Exception {

    final StepContext stepContext = chunkContext.getStepContext();
    final String jobName = stepContext.getJobName();
    final JobParameters jobParams = stepContext.getStepExecution().getJobParameters();
    final Map<String, JobParameter> currParams = new HashMap<String, JobParameter>(jobParams.getParameters());
    currParams.remove("run.id");

    Date lastJobRun = null;

    final List<JobInstance> jobInstances = jobExplorer.getJobInstances(jobName, 0, 1000);
    for (final JobInstance jobInstance : jobInstances) {
        final List<JobExecution> jobExecutions = jobExplorer.getJobExecutions(jobInstance);
        for (final JobExecution jobExecution : jobExecutions) {

            final JobParameters oldJobParams = jobExecution.getJobParameters();
            final Map<String, JobParameter> oldParams = new HashMap<String, JobParameter>(
                    oldJobParams.getParameters());
            oldParams.remove("run.id");

            if (ExitStatus.COMPLETED.equals(jobExecution.getExitStatus()) && oldParams.equals(currParams)) {

                if (lastJobRun == null || lastJobRun.before(jobExecution.getStartTime())) {
                    lastJobRun = jobExecution.getStartTime();
                }
            }
        }
    }

    if (lastJobRun != null) {
        stepContext.getStepExecution().getExecutionContext().put("mantis.update.last_job_run", lastJobRun);
    }

    stepContext.getStepExecution().getExecutionContext().put("mantis.update.current_job_run",
            Calendar.getInstance());

    return RepeatStatus.FINISHED;
}

From source file:org.jasig.ssp.util.importer.job.tasklet.BatchFinalizer.java

@Override
public void afterJob(JobExecution jobExecution) {
    List<Throwable> failureExceptions = jobExecution.getAllFailureExceptions();

    if (failureExceptions != null) {
        for (Throwable failureException : failureExceptions) {
            if (ExceptionUtils.indexOfThrowable(failureException, JobInterruptedException.class) >= 0) {
                return;
            }/*from ww  w  . j a  v a  2  s  .  c o m*/
        }
    }
    logger.info("Files deleted and archived");
    Long diff = TimeUnit.MILLISECONDS
            .toMinutes(jobExecution.getEndTime().getTime() - jobExecution.getStartTime().getTime());

    logger.info("Job Duration in minutes: " + diff.toString());

    try {
        if (!archiveFiles.equals(ArchiveType.NONE)) {
            try {
                archive();
            } catch (Exception e) {
                logger.error("Error Archiving. Proceeding with file cleanup anyway.", e);
            }
        }
        // Always want to at least attempt clean up. Else behavior of next upload probably isn't what you expect.
        cleanDirectoryQuietly(processDirectory.getFile());
        cleanDirectoryQuietly(upsertDirectory.getFile());
        if (!retainInputFiles) {
            cleanCsvFilesQuietly(inputDirectory.getFile());
        }
    } catch (Exception e) {
        logger.error("Error Delete Process, Upsert And Input Directory", e);
    }
}

From source file:org.trpr.platform.batch.impl.spring.jmx.JobAdministrator.java

/**
 * Returns the JobStatistics array for all jobs deployed locally
 * @return JobStatistics array containing one instance per job deployed locally
 *//* w w w .  j a  v a 2 s .  c  o  m*/
private JobStatistics[] getStats() {

    JobStatistics[] jobStatistics = new JobStatistics[this.getJobOperator().getJobNames().size()];
    int count = 0;
    for (String jobName : this.getJobOperator().getJobNames()) {
        jobStatistics[count] = new JobStatistics();
        jobStatistics[count].setHostIP(this.getHostIP());
        jobStatistics[count].setHostStartTimeStamp(this.getHostStartTimeStamp());
        jobStatistics[count].setJobName(jobName);
        // get the last run JobInstance if any
        List<JobInstance> jobInstancesList = this.getJobExplorer().getJobInstances(jobName, 0, 1); // end is set as 1 to get a single element List
        if (jobInstancesList.size() > 0) { // there is at least one job instance 
            // get the first i.e. the most recent job instance
            JobInstance jobInstance = jobInstancesList.get(0);
            // now get all successful JobExecution(s) for this JobInstance
            List<JobExecution> jobExecutionList = this.getJobExplorer().getJobExecutions(jobInstance);
            if (jobExecutionList.size() > 0) { // there is at least one job execution for the job instance
                // get the first i.e. the most recent job execution
                JobExecution jobExecution = jobExecutionList.get(0);
                jobStatistics[count].setJobStatus(jobExecution.getStatus().name());
                if (jobExecution.getStatus() == BatchStatus.FAILED) { // try to get the exit description from the contained steps that errored out
                    Collection<StepExecution> stepExecutions = jobExecution.getStepExecutions();
                    for (StepExecution step : stepExecutions) {
                        jobStatistics[count].getJobSteps().add(step.getStepName());
                        if (step.getExitStatus().getExitCode().equals(ExitStatus.FAILED.getExitCode())) {
                            jobStatistics[count].setJobStepInError(step.getStepName());
                            jobStatistics[count].setJobMessage(step.getExitStatus().getExitDescription());
                        }
                    }
                } else {
                    jobStatistics[count].setJobMessage(jobExecution.getExitStatus().getExitDescription());
                }
                Calendar jobStartTimeStamp = Calendar.getInstance();
                jobStartTimeStamp.setTime(jobExecution.getStartTime());
                jobStatistics[count].setJobStartTimeStamp(jobStartTimeStamp);

                Calendar jobEndTimeStamp = Calendar.getInstance();
                jobEndTimeStamp.setTime(jobExecution.getEndTime());
                jobStatistics[count].setJobEndTimestamp(jobEndTimeStamp);
            }
        }
        count += 1;
    }
    return jobStatistics;
}