Hangfire - 在运行时为特定的 RecurringJob 配置 AutomaticRetry

Hangfire - Configure AutomaticRetry for specific RecurringJob at runtime

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

AutomaticRetryAttribute 声明您必须使用...

...a constant expression, typeof expression or an array creation expression of an attribute parameter type

...根据我的阅读,这是所有属性的典型特征。但是,这意味着我无法通过在其他地方设置 属性 值然后在包含我想要 运行.[=19= 的方法的 class 中引用它来实现我的目标]

此外,似乎没有任何方法可以在 BackgroundJob.EnqueueRecurringJob.AddOrUpdate 方法中配置自动重试属性。最后,我研究了你是否可以为每个命名队列使用特定的重试计数,但是你可以设置的关于 Hangfire 队列的唯一属性是它们在 Hangfire 服务器初始化时在 BackgroundJobServerOptions class 中的名称。

我在这里用尽了所有途径吗?我唯一能想到的另一件事是 create my own implementation of the AutomaticRetryAttribute and set the values at compile time 通过使用 int 枚举,尽管这本身会产生一个问题,因为我需要提供用户将需要的每个值的定义列表需要select。因为我希望重试次数可以配置为从 5 分钟一直到 1440 分钟(24 小时),我真的不想要一个巨大的、笨拙的 enum : int 每个可用值。有没有人遇到过这个问题,或者这是我应该在 Hangfire GitHub 上提交的请求吗?

我会采用制作自定义属性来装饰 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 的逻辑,而无需重复它。但是,如果您需要在每个作业的基础上更改更多方面,您可能需要在您自己的属性中复制逻辑。

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