Search code examples
asp.net-corehangfireasp.net-core-5.0

How to restart Hangfire server, or stop it and start a new one, to change the Queues it's processing?


In my asp.net 5 app I'm using Hangfire to process only certain Queues, based on which tenants the server should be looking after. So at app startup I look up which Queues and start the Hangfire server accordingly.

    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
    }

Sometime later I want to change the Queues that this server is processing. I think I need to just stop this hangfire server and start another one ... but a) how do I get a reference to this one, and b) how should I correctly start a new one, given that the advised method to start a Hangfire server in aspnet core is using services.AddHangfireServer()?


Solution

  • stop a running server

    BackgroundProcessingServer can be accessed in any controller after been injected

    _server.SendStop();
    await _server.WaitForShutdownAsync(new System.Threading.CancellationToken());
    _server.Dispose();
    

    start a new server

    AddHangfireServer can be triggered accessing an injected IApplicationBuilder

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

    startup.cs

      services.AddSingleton<IBackgroundProcessingServer, BackgroundProcessingServer>();
      services.AddSingleton<IApplicationBuilder, ApplicationBuilder>();
    

    Look here for a complete POC.

    Use JobStorage.Current.GetConnection().RemoveTimedOutServers(new TimeSpan(0, 0, 15)); to update /hangfire/servers