如何获得Hangfire工作的结束时间? [英] How can I get a Hangfire job's end time?

查看:146
本文介绍了如何获得Hangfire工作的结束时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于Hangfire作业的ID,我如何获得作业完成运行的时间?

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

我已经尝试了以下方法,但是 JobData 类没有作业结束时间的属性.

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);

推荐答案

我之前也有类似的要求.这是我编写的一种方法,该方法使用正在运行的方法的名称和当前的 PerformContext 来获取 SucceededAt 属性:

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;
}

您可以轻松获得 DeletedJobs EnqueuedJobs FailedJobs

您可以通过以下作业方法调用它:

You can call it from a job method like this:

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

添加作业时,只需传入 null :

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
        });

注意:仅当成功的作业尚未到期时,它才有效.成功的工作将在一天后到期-如果您需要将它们保留更长的时间(以获取 SucceededAt 属性),请参考以下内容:

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?

这篇关于如何获得Hangfire工作的结束时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆