如何获得 Hangfire 作业的结束时间?

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

给定一个 Hangfire 作业的 ID,我怎样才能得到作业完成的时间 运行?

我试过下面的方法,但是 JobData class 没有 属性 作业结束时间。

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

您可以尝试在第一次调用任务时使用 Stopwatch class 并在任务完成时停止它。

然后您可以使用日志块生成包含作业开始时间和结束时间的 txt 日志文件。或者直接将这些值保存到您的数据库中,以便您稍后查看。

我之前也有过类似的需求。这是我写的一个方法,使用 运行 方法的名称和当前 PerformContext:

获取 SucceededAt 属性
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;
}

您可以轻松获得 DeletedJobsEnqueuedJobsFailedJobs

您可以从这样的作业方法中调用它:

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

您只需在添加作业时通过传入 null:

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

注意:只有成功的任务还没有过期才会生效。成功的工作会在一天后过期 - 如果您需要将它们保留更长时间(以获得 SucceededAt 属性),这里有一个参考:How to configure the retention time of job?