private void BeginExecuteJob(JobDetails jobDetails) { ILogger jobLogger = logger.CreateChildLogger("Job: " + jobDetails.JobSpec.Name); JobExecutionContext context = new JobExecutionContext(this, jobLogger, jobDetails.JobSpec, jobDetails.JobSpec.JobData); try { jobLogger.InfoFormat("Job '{0}' started at {1}.", jobDetails.JobSpec.Name, jobDetails.LastJobExecutionDetails.StartTimeUtc); JobExecuteAsyncState asyncState = new JobExecuteAsyncState(jobDetails, context); jobRunner.BeginExecute(context, EndExecuteJob, asyncState); } catch (Exception ex) { DateTime endTime = DateTime.UtcNow; jobLogger.ErrorFormat(ex, "Job '{0}' failed because the job runner could not start it.", jobDetails.JobSpec.Name); jobDetails.LastJobExecutionDetails.Succeeded = false; jobDetails.LastJobExecutionDetails.EndTimeUtc = endTime; jobDetails.LastJobExecutionDetails.StatusMessage = String.Format(CultureInfo.CurrentCulture, "Job runner failed to start the job due to an exception:\n{0}", ex); jobDetails.JobState = JobState.Completed; jobStore.SaveJobDetails(jobDetails); } }
private void EndExecuteJob(IAsyncResult asyncResult) { string errorSource = "Undefined - (Failure to acquire AsyncState)"; try { JobExecuteAsyncState asyncState = (JobExecuteAsyncState)asyncResult.AsyncState; JobDetails jobDetails = asyncState.JobDetails; JobExecutionContext context = asyncState.Context; ILogger jobLogger = context.Logger; errorSource = jobDetails.JobSpec.Name; try { bool succeeded = jobRunner.EndExecute(asyncResult); DateTime endTime = DateTime.UtcNow; jobDetails.LastJobExecutionDetails.Succeeded = succeeded; jobDetails.LastJobExecutionDetails.EndTimeUtc = endTime; if (succeeded) { jobLogger.InfoFormat("Job '{0}' completed successfully at {1}.", jobDetails.JobSpec.Name, endTime); jobDetails.LastJobExecutionDetails.StatusMessage = "Completed successfully."; } else { jobLogger.ErrorFormat("Job '{0}' completed with an error at {1}.", jobDetails.JobSpec.Name, endTime); jobDetails.LastJobExecutionDetails.StatusMessage = "Completed with an unspecified error."; } jobDetails.JobSpec.JobData = context.JobData; } catch (Exception ex) { DateTime endTime = DateTime.UtcNow; jobLogger.ErrorFormat(ex, "Job '{0}' failed with an exception at {1}.", jobDetails.JobSpec.Name, endTime); jobDetails.LastJobExecutionDetails.Succeeded = false; jobDetails.LastJobExecutionDetails.EndTimeUtc = endTime; jobDetails.LastJobExecutionDetails.StatusMessage = String.Format(CultureInfo.CurrentCulture, "Job execution failed with an exception:\n{0}", ex); } jobDetails.JobState = JobState.Completed; jobStore.SaveJobDetails(jobDetails); } catch (Exception ex) { logger.FatalFormat(ex, "A fatal exception occurred while finalizing the execution of job '{0}'. " + "The job's updated status may not have been saved to the job store.", errorSource); } }