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

Fre*_*lom 7 c# asp.net-mvc hangfire

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

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

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

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

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

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

Xym*_*nek 6

我会采取制作自定义属性来装饰的方法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 = /**/ };
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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