Categories
Blog

hangfire

I’ve stumbled across an amazing ASP.NET / ASP.NET Core Background Job Scheduler called hangfire.

I cannot believe how amazing this is, how simple it is to use and how easy it was to implement it in my existing ASP.NET Core Web App.

One of the issues I stumble across quite a lot is handling the response timeout issue if I’m dealing with, either an incredible large amount of data, or waiting for another task to finish first. ASP.NET defaults to 90 seconds then disconnects the request, but the process still continues and may provide the response, but it’s been disconnected ­čÖü

So, one quick way to resolve this is use hangfire! There is a cool configuration option to turn your controllers into Services, so as long as you make the methods public that you wish to call in the background, it all runs as if it’s part of the same process.

So after a very quick configuration change, you simply tweak your controllers so the calls, actually just Enqueue the job the call would normally make! I.e. The Get() method becomes the DoGet() method and the new Get() method just Enqueues DoGet()!

You can pass in the parameters as well, but remember to pass in the type in your Enqueue command, e.g. Enqueue<InfoController>(p => p.Id == id).

Next problem is actually getting the response! Well 2 ways of doing this, 1 polling and 2. SignalR. I opted for the polling option as SignalR for ASP.NET Core is still beta, but when it is released, I will definitely switch to that option. I use a static variable to┬ácheck on the progress of the job and return the data when it’s complete, but you could use the Database.

Handling errors is fantastic too! If the process Throws an exception it is visible via the Dashboard, which is a great debug tool, and hangfire automatically tries the process again. So if you don’t want it to try again, don’t throw an exception! Otherwise, it’s a good idea to keep track of where you are in the process, as the process will always start again, and if the problem is at 99% you’ll be gutted that it’s doing all of it again for no reason to fail at that point again, or if it does continue this time, do all of it again to only do the last 1%!

My next job is automating these jobs, and hangfire can do all that for me too! Seems simple enough, just having the time to implement it! Oh! Remember if you are hosting it on IIS to make sure the Application Pool is set to Keep Alive.

Other than that, check it out, can’t believe it’s free too, and there’s a Pro license if you wish to have greater control over Batch jobs and get more support.