Hangfire获得最后执行时间

Sve*_*übe 5 c# asp.net hangfire

我正在使用hangfire 1.5.3。在我的定期工作中,我想调用一个使用自上次运行以来的时间的服务。不幸的LastExecution是,将其设置为当前时间,因为在执行作业之前已更新了作业数据。

工作

public abstract class RecurringJobBase
{
    protected RecurringJobDto GetJob(string jobId)
    {
        using (var connection = JobStorage.Current.GetConnection())
        {
            return connection.GetRecurringJobs().FirstOrDefault(p => p.Id == jobId);
        }
    }

    protected DateTime GetLastRun(string jobId)
    {
        var job = GetJob(jobId);

        if (job != null && job.LastExecution.HasValue)
        {

            return job.LastExecution.Value.ToLocalTime();
        }

        return DateTime.Today;
    }
}

public class NotifyQueryFilterSubscribersJob : RecurringJobBase
{
    public const string JobId = "NotifyQueryFilterSubscribersJob";
    private readonly IEntityFilterChangeNotificationService _notificationService;

    public NotifyQueryFilterSubscribersJob(IEntityFilterChangeNotificationService notificationService)
    {
        _notificationService = notificationService;
    }

    public void Run()
    {
        var lastRun = GetLastRun(JobId);
        _notificationService.CheckChangesAndSendNotifications(DateTime.Now - lastRun);
    }
}
Run Code Online (Sandbox Code Playgroud)

寄存器

RecurringJob.AddOrUpdate<NotifyQueryFilterSubscribersJob>(NotifyQueryFilterSubscribersJob.JobId, job => job.Run(), Cron.Minutely, TimeZoneInfo.Local);
Run Code Online (Sandbox Code Playgroud)

我知道,它是按分钟配置的,因此我可以大致计算时间。但是我想有一个独立于配置的实现。所以我的问题是:如何实现RecurringJobBase.GetLastRun返回上一次运行的时间?

And*_*eas 1

您可以利用您已经说过的事实 - “不幸的是,LastExecution 设置为当前时间,因为作业数据在执行作业之前已更新”。

该作业包含“LastJobId”属性,它似乎是一个递增的 Id。因此,您应该能够通过递减 LastJobId 并查询该 ID 的作业数据来获取“真实”的上一个作业。

var currentJob = connection.GetRecurringJobs().FirstOrDefault(p => p.Id == CheckForExpiredPasswordsId);

if (currentJob == null)
{
    return null; // Or whatever suits you
}

var previousJob = connection.GetJobData((Convert.ToInt32(currentJob.LastJobId) - 1).ToString());

return previousJob.CreatedAt;
Run Code Online (Sandbox Code Playgroud)

请注意,这是创建时间,而不是执行时间。但它对你来说可能足够准确。请记住第一次运行时的边缘情况,因此不会有以前的工作。