如何重新启动 Hangfire 服务器,或者停止它并启动一个新服务器,以更改它正在处理的队列?

Ror*_*ory 7 hangfire asp.net-core asp.net-core-5.0

在我的 asp.net 5 应用程序中,我使用 Hangfire 仅处理某些队列,基于服务器应照顾的租户。因此,在应用程序启动时,我会查找哪些队列并相应地启动 Hangfire 服务器。

    public void ConfigureServices(IServiceCollection services)
    {
        // ... do stuff

        services.AddHangfire(config => config
                                .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                                .UseSimpleAssemblyNameTypeSerializer()
                                .UseSqlServerStorage(hangfireConnectionString, new SqlServerStorageOptions
                                {
                                    QueuePollInterval = new TimeSpan(0, 0, 0, 0, 500)
                                })
        );

        string[] queueNames = GetQueueNamesForThisServerToProcess();

        services.AddHangfireServer(options =>
        {
            options.Queues = queueNames;
        });

        // ... do more stuff
    }
Run Code Online (Sandbox Code Playgroud)

稍后我想更改该服务器正在处理的队列。我我需要停止这个hangfire服务器并启动另一个...但是a)我如何获得对这个服务器的引用,b)鉴于建议的启动方法,我应该如何正确启动一个新的服务器aspnet core 中的 Hangfire 服务器正在使用services.AddHangfireServer()

ste*_*and 12

停止正在运行的服务器

注入后可以在任何控制器中访问BackgroundProcessingServer

_server.SendStop();
await _server.WaitForShutdownAsync(new System.Threading.CancellationToken());
_server.Dispose();
Run Code Online (Sandbox Code Playgroud)

启动一个新服务器

可以通过访问注入的 IApplicationBuilder 来触发 AddHangfireServer

  _applicationBuilder.UseHangfireServer(new BackgroundJobServerOptions
  {
    WorkerCount = 1,
    Queues = new[] { "customqueuename" },
    ServerName = "Custom server 2",
  });
Run Code Online (Sandbox Code Playgroud)

启动.cs

  services.AddSingleton<IBackgroundProcessingServer, BackgroundProcessingServer>();
  services.AddSingleton<IApplicationBuilder, ApplicationBuilder>();
Run Code Online (Sandbox Code Playgroud)

在此处查看完整的 POC

用于JobStorage.Current.GetConnection().RemoveTimedOutServers(new TimeSpan(0, 0, 15));更新 /hangfire/servers