2

I am currently using hangfire to en-queue jobs. The conventional way to en-queue a hangfire job is by using something like this:

 BackgroundJob.Enqueue(() => DoWork());

which will then intern en-queue and execute this job in the "DEFAULT" hangfire queue.

I can however add a attribute to the method which will intern be used to determine which queue it will be placed in and executed:

    [Queue("SECONDARY")]
    public void DoWork()
    {

    }

My question: Is there a way to to dynamically/programmatically en-queue a hangfire job in a specified queue with out using the above mentioned method attribute?

Pieter Alberts
  • 829
  • 1
  • 7
  • 23
Vipin
  • 938
  • 5
  • 18
  • 36

1 Answers1

2

Here is some pseudo-code for you.

https://api.hangfire.io/html/M_Hangfire_BackgroundJobClient_Create.htm

class Program
{
    static void Main(string[] args)
    {
        EnqueuedState queue = new EnqueuedState("myQueueName");
        new BackgroundJobClient().Create<Program>(c => c.DoWork(), queue);
    }

    public void DoWork()
    {

    }
}

The other option I am aware of is to make use of an interface and indirectly make use of the attribute. See pseudo-code below:

 {
     interface IHangfireJob
     {
         [Queue("secondary")]
         void Execute();
     }
 }

 class Program : IHangfireJob
 {
     static void SomeMainMethod()
     {
        BackgroundJob.Enqueue(() => Execute());
     }

     public void Execute()
     {
        Console.WriteLine("Fire-and-forget!");
     }
 }
Pieter Alberts
  • 829
  • 1
  • 7
  • 23
  • Thanks for the reply. The above code will work to queue to specific queue. But I have aproblem. Let us assume , we are having two queue default and secondary. Suppose i queued job to the secondary queue using above method. And it got failed. When it retry . It is try to retry in default queue. But i want it to do in secondary queue. How to achieve it? – Vipin Oct 03 '18 at 15:00
  • Have you considered using an interface ? See my updated answer above. If that is not going to work for you, then i am out of ideas ;-P Hope someone else can help you. Good luck. – Pieter Alberts Oct 04 '18 at 06:13
  • Pieter Alberts. By using interface we can achieve. As I told earlier in my question i don't want to use attribute. Because your first approach work. But when the job failed and try to retry it will come to default queue – Vipin Oct 05 '18 at 14:52