Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use custom job name when using HangFire to start jobs that implement an interface

I'm attempting to use HangFire to schedule any class that implements a certain interface I have called IScheduledService. These services run as expected, but HangFire UI always shows the same name for each service in the HangFire dashboard PerformService(). I know this is by design because I'm passing the same function name into each job, but users don't really know what specific job is running.

I created the interface with ServiceName because I thought may be able to pass that into HangFire to override the visible job name instead of the name of the function being called, but don't see the ability to modify the job name. Is there a way to provide a custom job name so that the HangFire UI will show the title of each job based on the value of ServiceName property?

public interface IScheduledService
{
    string ServiceId { get; }
    string ServiceName { get; }
    void PerformService();
}

public class Service1 : IScheduledService
{
    public string ServiceId { get => "e56643b1-f0cf-44b2-81ef-bf7a085de760"; }
    public string ServiceName { get => this.GetType().Name; }

    public void PerformService()
    {
        Console.WriteLine($"Hello world from {ServiceName}");
    }
}
like image 972
Geekn Avatar asked Nov 11 '19 13:11

Geekn


People also ask

How does a Hangfire fire and forget background job allow you to run a background job?

Hangfire handles different types of background jobs, and all of them are invoked in a separate execution context. Fire and forget jobs are executed once on an immediate basis after creation. Once you create a fire-and-forget job, it is saved to its queue ("default" by default, but multiple queues supported).

What Hangfire object and method is used to create a recurring job?

The call to AddOrUpdate method will create a new recurring job or update existing job with the same identifier.


1 Answers

You can display multiple arguments. In my implementation, I have DisplayName instead of JobDisplayName (Hangfire ver 1.7.5)

public static class Func 
{
   [DisplayName("JobID: {0} => [{1}:{2}]")]
   public static void Execute(long requestID, string stepName, string stepLocation)
   {
      // do work here
   }
}

// above method is called by the background.enqueue call
BackgroundJob.Enqueue(() => Func.Execute(longId, stepName, stepLocation);

That seems to provide the information relevant to the job that is executed.

like image 187
Jawad Avatar answered Oct 05 '22 02:10

Jawad