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

标签 c# asp.net-mvc hangfire

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

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



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

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

我是否已经用尽了这里的所有途径?我唯一能想到的就是create my own implementation of the AutomaticRetryAttribute and set the values at compile time通过使用 int 枚举,虽然这本身会产生一个问题,因为我需要提供用户需要选择的每个值的定义列表。由于我希望重试次数可配置为从 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>在每个作业的基础上存储任意数据

关于c# - Hangfire - 在运行时为特定的 RecurringJob 配置 AutomaticRetry,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60669289/

相关文章:

c# - 在 wpf 中重复打开对话框时的性能问题

c# - 文件同步

c# - Hangfire RecurringJob + 简单注入(inject)器 + MVC

c#-4.0 - 针对特定异常的 Hangfire 自动重试

c# - hangfire 重试如何在 recuringjob 中工作?

c# - 在我的应用程序中使用 sdk 的 dll 而无需复制和注册

c# - Volatile 违反了它的主要工作?

asp.net-mvc - 将输入类型文件与 ASP.Net MVC 一起使用时,Request.Files 为空

c# - EditorFor/CheckBoxFor bool 值将 data-val-required 属性添加到 HTML,而无需将 required 属性添加到模型

asp.net-mvc - ASP.NET MVC : Triggering an action before posting to Paypal payment gateway