【问题标题】:Can hang-fire throttle number of background jobs running in parallel可以挂起限制并行运行的后台作业的数量
【发布时间】:2018-07-23 23:32:02
【问题描述】:

我有 IO 密集型方法,我正在使用 hangfire 作为后台作业运行。

public IHttpActionResult Request(int[] ids)
{
    foreach(var id in ids)
    {
       BackgroundJob.Enqueue<IMyService>(x => x.DoWork(id));
    }
}

因此,对于每个 id,我将一个后台作业排入队列,然后 hangfire 立即按预期调用 DoWork()。但是DoWork 是 IO 密集型的。因此,如果我有 100 多个 id,则需要大量 CPU 功率和带宽

有没有办法限制 Hangfire 中后台作业的数量

【问题讨论】:

    标签: c# hangfire hangfire-sql


    【解决方案1】:

    您可以使用 hangfire queues 并设置该队列的工作人员数量。

    在您的 hangfire 启动配置中设置以下队列:

    var options = new BackgroundJobServerOptions
    {
        Queues = new[] { "default" }, // You can have multiple queues and multiple worker counts.. check hangfire documentation
        WorkerCount = 5 // this is up to you
    };
    
    app.UseHangfireServer(options);
    

    参见下面的代码示例:

    public IHttpActionResult Request(int[] ids)
    {
        foreach(var id in ids)
        {
           BackgroundJob.Enqueue<IMyService>(x => x.DoWork(id));
        }
    }
    
    
    [Queue("default")]// add this attribute on your function
    public void DoWork() { 
        //Magical IO code here
    }
    

    如果您需要更多信息,我建议您查看以下 hangfire 文档: http://docs.hangfire.io/en/latest/background-processing/configuring-degree-of-parallelism.html https://discuss.hangfire.io/t/different-queues-having-different-worker-counts/114

    希望这会有所帮助。

    【讨论】:

    • 我用过它,它应该也能解决你的问题:-)
    • 是的 MaximumConcurrentExecutions 工作。我注意到一件事,我将Unity 用于 DI。如果您使用接口BackgroundJob.Enqueue&lt;IMyService&gt;(x =&gt; x.DoWork(id)); Then you have to add MaximumConcurrentExecutions`属性在接口中的方法定义上注册后台作业,而不是在具体类中
    • 有趣。感谢更新。看起来你解决了自己的问题。请发布您的答案,以便我为您投票:-)
    • 所以遇到了MaximumConcurrentExecutionsAttribute 的另一个问题。 MaxConcurrentJobs 的任何小于 20 的值都按预期工作,但任何大于 20 的值仅执行 20 个作业。例如 [MaximumConcurrentExecutions(100, 120, 10)] 这一次只执行 20 个作业
    猜你喜欢
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    • 2011-09-24
    • 1970-01-01
    相关资源
    最近更新 更多