getting last successful job run hangfire status code example

Example: getting last successful job run hangfire status

var jobName = performContext.BackgroundJob.Job.ToString();
var currentJobId = int.Parse(performContext.BackgroundJob.Id);
JobData jobFoundInfo = null;

using (var connection = JobStorage.Current.GetConnection()) {
    var decrementId = currentJobId;
    while (decrementId > currentJobId - 50 && decrementId > 1) { // try up to 50 jobs previously
        decrementId--;
        var jobInfo = connection.GetJobData(decrementId.ToString());
        if (jobInfo.Job.ToString().Equals(jobName)) { // **THIS IS THE CHECK**
            jobFoundInfo = jobInfo;
            break;
        }
    }
    if (jobFoundInfo == null) {
       throw new Exception($"Could not find the previous run for job with name {jobName}");
    }
    return jobFoundInfo;
}

Tags:

Misc Example