How can I get a Hangfire job's end time?

左心房为你撑大大i 提交于 2021-01-07 06:30:46

问题


Given a Hangfire job's ID, how can I get the time at which the job finished running?

I've tried the below, but the JobData class doesn't have a property for job end time.

IStorageConnection connection = JobStorage.Current.GetConnection();
JobData jobData = connection.GetJobData(jobId);

回答1:


I have had a similar requirement before. Here is a method I wrote to get the SucceededAt property using the name of the running method and the current PerformContext:

public static DateTime? GetCompareDate(PerformContext context, string methodName)
{
    return long.TryParse(context.BackgroundJob.Id, out var currentJobId)
        ? JobStorage.Current
            ?.GetMonitoringApi()
            ?.SucceededJobs(0, (int)currentJobId)
            ?.LastOrDefault(x => x.Value?.Job?.Method?.Name == methodName).Value?.SucceededAt
        : null;
}

You could just as easily get DeletedJobs, EnqueuedJobs, FailedJobs, etc.

You can call it from a job method like this:

public async Task SomeJob(PerformContext context, CancellationToken token)
{
    ⋮
    var compareDate = GetCompareDate(context, nameof(SomeJob));
    ⋮
}

You just have to add the PerformContext when adding the job by passing in null:

RecurringJobManager.AddOrUpdate(
        recurringJobId: "1",
        job: Job.FromExpression(() => SomeJob(null, CancellationToken.None)),
        cronExpression: Cron.Hourly(15),
        options: new RecurringJobOptions
        {
            TimeZone = TimeZoneInfo.Local
        });

Note: It will only work if the succeeded job has not expired yet. Successful jobs expire after one day - if you need to keep them longer (to get the SucceededAt property), here is a reference for that: How to configure the retention time of job?




回答2:


You could try using the Stopwatch class when you first call the task and stop it when the task is completed.

Then you could use a log nugget to generate a txt log file containing the start time and end time of your job. Or directly save this values to your database so that you can review them later.



来源:https://stackoverflow.com/questions/58174699/how-can-i-get-a-hangfire-jobs-end-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!