避免hangfire作业重复的提示?

时间:2020-05-14 19:06:22

标签: c# parallel-processing hangfire hangfire-sql

我遇到的问题是,一些使用相同参数的hangfire上的作业被多次排队,而这些作业几乎同时被排队。

我试图将工人人数限制为一个,然后用DisableConcurrentExecution装饰我的方法。

我正在使用sqlserver作为存储。任何人都遇到过这个问题,有一些避免的技巧?

PS:我使用DisableConcurrentExecution是因为在hangfire文档中,互斥体和信号量不能保证仅一次调用该作业。

PS2:检查我的hangfire服务器,我注意到我有两个实例,每个实例有1个工作程序,所以我认为这是一个并行性问题,而不是并发的。

2 个答案:

答案 0 :(得分:2)

根据Hangfire documentation,当重复的作业/任务没有标识符时,就会出现重复作业问题:“为每个重复的作业使用唯一的标识符,否则您将以单个作业结束。 “

NaT

来源:

  1. https://gist.github.com/odinserj/a8332a3f486773baa009;
  2. https://discuss.hangfire.io/t/how-do-i-prevent-creation-of-duplicate-jobs/1222/4;

答案 1 :(得分:0)

这项工作对我有用。我用MaximumConcurrentExecutions(1)装饰了hangfire运行的接口方法。

这并不能单独解决我的问题,因为有多个服务器(自动扩展)。

因此,在启动类中,我创建了另一个backgroundjobserver选项来创建此作业的独占服务器,以确保在应用程序扩展时不会创建具有另一个队列的其他服务器,我必须在sqlserver hangfire.server中进行查询,并检查我的队列是否已经存在。

if(!HangfireServerInfo.QueueExists("queuename", AppSettings.GetConnectionString("Hangfire"))){
        var hangfireServerOptions = new BackgroundJobServerOptions { WorkerCount = 1, Queues = new[] {"queuename"} };
        app.UseHangfireServer(hangfireServerOptions);
    }


public static class HangfireServerInfo
    {
        public static bool QueueExists(string queueName, string connectionString)
        {
            using (var connection = new SqlConnection(connectionString))
            {
                var cmd = connection.CreateCommand();
                cmd.CommandText = 
                    $@"SELECT COUNT(*) 
                    FROM {YOURHANGFIRESERVER.server}
                    WHERE JSON_QUERY(data, '$.queues') = '[""{queueName}""]'";

                connection.Open();
                var result = (int)cmd.ExecuteScalar();
                connection.Close();

                return result > 0;
            }
        }
    }

也许是解决它的更好方法,但这是可行的。

相关问题