Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In HangFire, can I Enqueue with a queue name instead of using the Queue attribute?

Tags:

hangfire

This documentation says that you can specify a queue by using the Queue attribute on the method to be invoked. This assumes that you always want execute a method on the same queue. Is there a way for the process that calls Enqueue to specify the name of the queue to put the job into (effectively putting the decision-making in the hands of the job generator, not the definition of the job).

like image 288
SFun28 Avatar asked Apr 23 '15 13:04

SFun28


2 Answers

With a instance of IBackgroundJobClient you can specify a queue.

IBackgroundJobClient hangFireClient = new BackgroundJobClient();
EnqueuedState myQueueState = new Hangfire.States.EnqueuedState("myQueue");
hangFireClient.Create<SomeClass>(c => c.SomeMethod(), myQueueState);

Note that in this way, a retry will put the job back to the default queue. You will require additional code to retry in the same queue, using a JobFilter

http://discuss.hangfire.io/t/one-queue-for-the-whole-farm-and-one-queue-by-server/490/3

like image 191
Xavero Avatar answered Sep 21 '22 13:09

Xavero


Since adding an extra parameter seems to be so hard for the Hangfire team ;-)....

...I've found the most convenient way is to make two methods that just call the actual implementation, and put different [Queue] attributes on each.

Usually if I need to switch queues it's between dev / production and I want to just call something like RunOrder(...) with isTestOrder=boolean and not be concerned about queues at that level.

public void RunOrder(int orderId, bool isTestOrder) 
{
   if (isTestOrder) 
   {
      BackgroundJob.Enqueue(() => _RunTestOrder(orderId));
   } 
   else 
   {
      BackgroundJob.Enqueue(() => _RunOrder(orderId));
   }
}

[Queue("dev")]
public void _RunTestOrder(int orderId) {
  OrderProcessor.RunOrder(orderId); // actual code to call processor
}

[Queue("production")]`
public void _RunProductionOrder(int orderId) {
  OrderProcessor.RunOrder(orderId); // is the same in both 'hangfire proxies'
}

Note usage of _ to indicate these aren't meant to be called directly. I don't remember off hand if hangfire methods need to be public or not - but if they do need to be then the _ is more important.

like image 39
Simon_Weaver Avatar answered Sep 20 '22 13:09

Simon_Weaver