如何在Hangfire中的后台作业中获取当前尝试号码?

时间:2016-07-14 07:33:15

标签: asp.net-mvc scheduled-tasks hangfire

在我的Hangfire后台作业的最终尝试结束之前,我需要执行一些数据库操作(我需要删除与作业相关的数据库记录)

我当前的工作设置了以下属性:
[AutomaticRetry(Attempts = 5, OnAttemptsExceeded = AttemptsExceededAction.Delete)]

考虑到这一点,我需要确定当前的尝试号码是什么,但我很难通过Google搜索或Hangfire.io文档找到这方面的任何文档。

3 个答案:

答案 0 :(得分:13)

只需将table.schema = [field for field in table.schema if field.name != 'TEST'] 添加到您的工作方法中;您还可以从此对象访问PerformContext。对于尝试号码,这仍然依赖于魔术字符串,但它比当前/唯一的答案稍微不那么简单:

JobId

答案 1 :(得分:5)

如果您想检查尝试,或者您希望等待OnPerforming OnPerformed,您可以使用IServerFilterOnStateElection IElectStateFilter方法}。我不知道你有什么要求,所以这取决于你。这是您想要的代码:)

public class JobStateFilter : JobFilterAttribute, IElectStateFilter, IServerFilter
{
    public void OnStateElection(ElectStateContext context)
    {
        // all failed job after retry attempts comes here
        var failedState = context.CandidateState as FailedState;

        if (failedState == null) return;
    }

    public void OnPerforming(PerformingContext filterContext)
    {
        // do nothing
    }

    public void OnPerformed(PerformedContext filterContext)
    {
        // you have an option to move all code here on OnPerforming if you want.
        var api = JobStorage.Current.GetMonitoringApi();

        var job = api.JobDetails(filterContext.BackgroundJob.Id);

        foreach(var history in job.History)
        {
            // check reason property and you will find a string with
            // Retry attempt 3 of 3: The method or operation is not implemented.            
        }
    }   
}

如何添加过滤器

GlobalJobFilters.Filters.Add(new JobStateFilter());

----- or 

var options = new BackgroundJobServerOptions
{   
    FilterProvider = new JobFilterCollection { new JobStateFilter() };
};

app.UseHangfireServer(options, storage);

示例输出:

enter image description here

答案 2 :(得分:4)

(注意!这是OP问题的解决方案。它没有回答“如何获取当前尝试次数”的问题)

使用作业过滤器和OnStateApplied回调:

public class CleanupAfterFailureFilter : JobFilterAttribute, IServerFilter, IApplyStateFilter
{
    public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
    {
        try
        {
            var failedState = context.NewState as FailedState;
            if (failedState != null)
            {
                // Job has finally failed (retry attempts exceeded)
                // *** DO YOUR CLEANUP HERE ***
            }
        }
        catch (Exception)
        {
            // Unhandled exceptions can cause an endless loop.
            // Therefore, catch and ignore them all.
            // See notes below.
        }
    }

    public void OnStateUnapplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
    {
        // Must be implemented, but can be empty.
    }
}

将过滤器直接添加到作业功能:

[CleanupAfterFailureFilter]
public static void MyJob()

或全局添加:

GlobalJobFilters.Filters.Add(new CleanupAfterFailureFilter ());

或者像这样:

var options = new BackgroundJobServerOptions
{   
    FilterProvider = new JobFilterCollection { new CleanupAfterFailureFilter () };
};

app.UseHangfireServer(options, storage);

或者有关作业过滤器的详情,请参阅http://docs.hangfire.io/en/latest/extensibility/using-job-filters.html

注意:这取决于接受的答案:https://stackoverflow.com/a/38387512/2279059

不同之处在于使用OnStateApplied而不是OnStateElection,因此仅在最大重试次数后才调用过滤器回调。这种方法的一个缺点是状态转换为“失败”不能被中断,但在这种情况下并不需要这样做,并且在大多数情况下你只想在作业失败后进行一些清理。

注意:空的catch处理程序很糟糕,因为它们可以隐藏错误并使它们难以在生产中进行调试。这是必要的,因此回调不会被永远重复调用。您可能希望记录异常以进行调试。建议降低作业过滤器中的异常风险。一种可能性是,不是在原地执行清理工作,而是安排在原始作业失败时运行的新后台作业。但是,请注意不要将过滤器CleanupAfterFailureFilter应用于它。不要全局注册,或者为它添加一些额外的逻辑......