Hangfire.MaximumConcurrentExecutions 使用教程

Hangfire.MaximumConcurrentExecutions 使用教程

Hangfire.MaximumConcurrentExecutions Adds [MaximumConcurrentExecutions(n)] attribute to Hangfire.IO to throttle executions of a job Hangfire.MaximumConcurrentExecutions 项目地址: https://gitcode.com/gh_mirrors/ha/Hangfire.MaximumConcurrentExecutions

1. 项目介绍

Hangfire.MaximumConcurrentExecutions 是一个开源项目,它为 hangfire.io 添加了一个新的作业过滤属性 [MaximumConcurrentExecutions(n)]。这个属性允许开发者轻松地限制同一时间运行的作业数量。它使用分布式锁,即使在多节点环境下也能正常工作。

2. 项目快速启动

安装

首先,确保您已经安装了 Hangfire。如果没有,请参考 Hangfire 快速入门

接下来,使用 NuGet 包管理器安装 Hangfire.MaximumConcurrentExecutions 属性。在包管理器控制台中输入以下命令:

Install-Package Hangfire.MaximumConcurrentExecutions

配置作业

然后,使用 [MaximumConcurrentExecutions(n)] 属性装饰您的作业。以下是一个示例:

public class ExampleJob
{
    [MaximumConcurrentExecutions(3)]
    public void SomeLongRunningActivity()
    {
        Console.WriteLine("开始作业");
        Task.Delay(TimeSpan.FromSeconds(5)).Wait();
    }
}

队列作业

最后,将作业添加到后台队列中:

BackgroundJob.Enqueue<ExampleJob>(job => job.SomeLongRunningActivity());

3. 应用案例和最佳实践

设置超时

当使用 MaximumConcurrentExecutions 属性时,所有可用的工作者都会将新作业放入进行中状态,但如果有超过 maxConcurrentJobs 已经在运行,它们将不会开始执行。默认情况下,如果在60秒内没有其他工作者完成相同作业的分布式锁变得可用,作业将抛出异常。要更改此设置,可以设置 timeoutInSeconds 参数,例如,对于2分钟的超时时间:

public class ExampleJob
{
    [MaximumConcurrentExecutions(3, timeoutInSeconds = 120)]
    public void SomeLongRunningActivity()
    {
        // ...
    }
}

设置轮询间隔

一旦所有可用的锁都被占用,并且最大数量的作业同时运行,我们需要轮询存储来检查释放的锁。为了避免消耗不必要的资源,您可能需要配置轮询的频率。如果您的作业运行时间为2分钟,您应该避免每分钟轮询超过一次:

public class ExampleJob
{
    [MaximumConcurrentExecutions(3, timeoutInSeconds = 120, pollingIntervalInSeconds = 60)]
    public void SomeLongRunningActivity()
    {
        // ...
    }
}

4. 典型生态项目

目前,Hangfire.MaximumConcurrentExecutions 项目没有列出特定的生态项目。但是,任何使用 Hangfire 作为后台作业处理系统的项目都可以集成此属性以更好地控制作业执行的数量和性能。

Hangfire.MaximumConcurrentExecutions Adds [MaximumConcurrentExecutions(n)] attribute to Hangfire.IO to throttle executions of a job Hangfire.MaximumConcurrentExecutions 项目地址: https://gitcode.com/gh_mirrors/ha/Hangfire.MaximumConcurrentExecutions

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

倪焰尤Quenna

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值