首页 > 解决方案 > Hangfire - 在运行时为特定的 RecurringJob 配置 AutomaticRetry

问题描述

我正在使用 Hangfire v1.7.9,并尝试在我的 MVC 5 应用程序中配置一系列重复的后台作业,以自动将外部参考数据检索到应用程序中。我已经用一项任务对此进行了测试,效果很好,但我希望系统内的管理员能够配置与在这些后台作业中调用的方法相关联的参数Attempts和属性参数。DelayInSeconds

AutomaticRetryAttribute您必须使用的状态...

...属性参数类型的常量表达式、typeof 表达式或数组创建表达式

...从我读过的内容来看,这是所有属性的典型特征。但是,这意味着我无法通过在其他地方设置属性值然后在包含我要运行的方法的类中引用它来实现我的目标。

此外,看起来没有任何方法可以在BackgroundJob.EnqueueorRecurringJob.AddOrUpdate方法中配置自动重试属性。最后,我查看了您是否可以为每个命名队列使用特定的重试计数,但遗憾的是,您可以设置的关于 Hangfire 队列的唯一属性是它们在BackgroundJobServerOptionsHangfire 服务器初始化时在类中的名称。

我用尽了这里的每一条途径吗?我能想到的唯一另一件事是创建我自己的 AutomaticRetryAttribute 实现并在编译时使用 int 枚举设置值,尽管这本身会产生一个问题,因为我需要提供一个定义的列表用户需要选择的每个值。因为我希望重试次数可以从 5 分钟一直到 1440 分钟(24 小时)进行配置,所以我真的不想要一个巨大的、笨拙enum : int的每个可用值。有没有人遇到过这个问题,或者这是我应该在 Hangfire GitHub 上作为请求提交的东西吗?

标签: c#asp.net-mvchangfire

解决方案


我会采用制作自定义属性的方法来装饰AutomaticRetryAttribute

public class MyCustomRetryAttribute : JobFilterAttribute, IElectStateFilter, IApplyStateFilter
{
    public void OnStateElection(ElectStateContext context)
    {
        GetAutomaticRetryAttribute().OnStateElection(context);
    }

    public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
    {
        GetAutomaticRetryAttribute().OnStateApplied(context, transaction);
    }

    public void OnStateUnapplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
    {
        GetAutomaticRetryAttribute().OnStateUnapplied(context, transaction);
    }

    private AutomaticRetryAttribute GetAutomaticRetryAttribute()
    {
        // Somehow instantiate AutomaticRetryAttribute with dynamically fetched/set `Attempts` value
        return new AutomaticRetryAttribute { Attempts = /**/ };
    }
}

编辑:为了澄清,这种方法允许您重用AutomaticRetryAttribute's 的逻辑,而无需复制它。但是,如果您需要在每个作业的基础上更改更多方面,您可能需要在自己的属性中复制逻辑。

此外,您可以使用context.GetJobParameter<T>基于每个作业存储任意数据


推荐阅读