2

We're trying to get the Hangfire ServerName from a running background job. Is this possible and if so, how?

So far, we've looked at the ProcessContext object, but it doesn't seem to include the ServerName.

Thank you for the help.

Garrett Vlieger
  • 9,354
  • 4
  • 32
  • 44

2 Answers2

1

A blind shot (not tested), but I would try something like this with an IApplyStateFilter :

public class GetServerIdFilter : IApplyStateFilter
{
    public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
    {
        var state = context.NewState as ProcessingState;
        if (state != null)
        {
            var serverId = state.ServerId;
            var workerId = state.WorkerId;
        }
    }

    public void OnStateUnapplied(ApplyStateContext context, IWriteOnlyTransaction transaction)
    {
    }
}

The filter can be registered as in this answer

jbl
  • 15,179
  • 3
  • 34
  • 101
0

I know the following doesn't quite answer your question about reading it from a job, as far as I've seen it looks impossible. If it is impossible, this answer might be helpful, so here you go.

I'm not sure there is an option to read it from somewhere.

Anyway, the Hangfire docs here read you could handle the server name manually:

Since the defaults values provide uniqueness only on a process level, you should handle it manually if you want to run different server instances inside the same process:

var options = new BackgroundJobServerOptions
    {
        ServerName = String.Format(
            "{0}.{1}",
            Environment.MachineName,
            Guid.NewGuid().ToString())
    };

    var server = new BackgroundJobServer(options);

    // or

    app.UseHangfireServer(options);
Dennis VW
  • 2,977
  • 1
  • 15
  • 36
  • 1
    Thanks. We're using the `BackgroundJobServerOptions` to create the servers, but the problem we're trying to solve is how to get which server is being used to run the job in a multi-server situation. We need to know which server in the pool gets chosen when the job is executed. – Garrett Vlieger Sep 19 '19 at 18:24