每个服务器上的hangfire周期性作业 [英] hangfire recurring job on every server

查看:208
本文介绍了每个服务器上的hangfire周期性作业的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这样的情况,我需要在hangfire中注册一个定期作业才能在群集中的每台服务器上运行.

I have a situation where I need a recurring job registered with hangfire to run on every server in the cluster.

(工作是在本地复制一些文件,因此需要定期在每台服务器上运行)

(The job is to copy some files locally so needs to run on every server regularly)

到目前为止,我已经尝试用服务器名称的ID注册相同的作业,导致n台服务器的n份作业:

So far I have tried registering the same job with an id of the server name resulting in n job for n servers:

RecurringJob.AddOrUpdate(Environment.MachineName, () => CopyFiles(Environment.MachineName), Cron.MinuteInterval(_delay));

作业本身会检查它是否是正确的服务器,并且仅在以下情况下才执行某些操作:

and the job itself checks if it is the correct server and only does something if it is:

 public static void CopyFiles(string taskId)
 {
        if (string.IsNullOrWhiteSpace(taskId) || !taskId.Equals(Environment.MachineName))
        {
            return;
        }

        // do stuff here if it matches our taskname
}

问题在于,所有作业均在要出现的第一个服务器上执行,被标记为已完成,因此其他服务器未执行.

The problem with this is that all jobs executes on the first server to come along, is marked as complete and as a result is not executed by the other servers.

有什么方法可以确保作业在所有服务器上运行?

Is there any way to ensure that the job runs on all servers?

还是有一种方法可以确保只有一台服务器可以处理给定的作业?即将作业定位到创建该作业的服务器上

or is there a way to ensure that only one server can process a given job? i.e. target the job at the server that created it

推荐答案

使用此链接.

只需将作业分配到特定于您要对其进行处理的服务器的队列.

Simply assign the job to a queue that is specific to the server you want it processing on.

所以我将队列更改为:

RecurringJob.AddOrUpdate(Environment.MachineName, 
  () => CopyFiles(Environment.MachineName),
  Cron.MinuteInterval(_delay), 
  queue: Environment.MachineName.ToLower(CultureInfo.CurrentCulture));

当我启动服务器时,我会这样做:

And when I start my server I do this:

_backgroundJobServer = new BackgroundJobServer(new BackgroundJobServerOptions 
                           {
                               Queues = new[] { Environment.MachineName.ToLower() } 
                           });

这篇关于每个服务器上的hangfire周期性作业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆