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