Recently I came across a requirement in a .Net Web API project to handle some time consuming requests to another system which is beyond from my control. Because of this users have to wait till the requests are completed. So to overcome the issue my team came up with Hangfire; a cool open source queue which is an easy way to perform fire-and-forget, delayed and recurring tasks inside ASP.NET applications.
In this posts I’m going to talk about the configuration and some features I used in my project but if you browse through the official site you can come across may other features in the Hangfire tool.
Hangfire have allowed developers to add Hangfire to project through Manage NuGet Packages. once you install Hangfire, two other components will be installed to your project which are depended.
Configure Mutiple Hangfire Servers
To configure Hangfire you need to do the following.
In Global.asax.cs file of you Web Api Project add the following code to Application_Start() method. By placing this code you will configure Hangfire and Sql Server. In my case I have configure my Data Context.
Now we have to tell our application to initialize Hangfire. In Startup.cs add the following code to the Configuration(IAppBuilder app) method. This where you have to specify the servers and queues you will be needing in your project.
In my user requirement I need to create two servers with single queues with different worker counts. I have one queue in one server with one worker count and another with more than one worker counts. one server with sequential processing and one with multiple processing at a time.
Now I’ll show you how to use the in your code. Following code shows how to direct the method to be executed to the correct queue.
MethodToExcute() >>> Method that you are going to queue in Hangfire.
Hangfire has it own amazing dashboard where you can track the progress and the status of the tasks you have queued.
This is the two servers which was created from the above code.
These are some feature I used from Hangfire tool. there are more features that can be used by you in your projects. You can Schedule, Delay tasks in the queues.