Hangfire坚持本地范围

时间:2020-01-10 22:13:41

标签: c# hangfire

我想使用Hangfire创建长时间运行的火灾并忘记任务。如果Web服务器死了并且重试了后台作业,我希望它从中断的地方继续。

在下面的示例中,假设foo.RetryCount达到3->服务器重新启动-> Hangfire重新运行该作业。在这种情况下,我只想再运行7次(基于MaxAttemps),而不是从零开始重启。

我以为Hangfire在当前状态下保留了传递给方法的参数,但据我所知,它们已被重置。

var foo = new Foo { RetryCount = 0, MaxAttemps = 10 };
BackgroundJob.Enqueue(() => RequestAndRetryOnFailure(foo));

void RequestAndRetryOnFailure(Foo foo) 
{
    // make request to server, if fail, wait for a 
    // while and try again later if not foo.MaxAttemps is reached
    foo.RetryCount++;
}

1 个答案:

答案 0 :(得分:1)

我将hangfire广泛用于许多不同的动作,并且始终需要重新计划已开始但由于某些限制而无法执行的作业。

您所指的持久性发生在已序列化的作业版本中,该版本已被执行,但是一旦执行便不再保留。

我建议,如果服务器不可用,则安排作业在一定数量后执行。如果计划了作业并且hangfire重新启动,这也将有助于重新启动作业。

var foo = new Foo { RetryCount = 0, MaxAttemps = 10 };
BackgroundJob.Enqueue(() => RequestAndRetryOnFailure(foo));

void RequestAndRetryOnFailure(Foo foo) 
{
    // make request to server, if fail, wait for a 
    // while and try again later if not foo.MaxAttemps is reached
    if (request to server failed) 
    {
        foo.RetryCount ++;
        If (foo.RetryCount < foo.MaxAttempts)
            BackgroundJob.Schedule(RequestAndRetryOnFailure(foo), Timespan.FromSeconds(30));
        else
             return; // do nothing
    }
}
相关问题