Peter Nguyen Team : Web Development Tags : Web Development

Using Hangfire for managing background tasks on your website

Peter Nguyen Team : Web Development Tags : Web Development

Creating background tasks for .net applications have always been a big task for any developer.

If you create it as a Windows Service, you will need to deal with separate application configurations, permission issues, UAC, Windows Server maintenance and potential offline periods. What happens if your service is scheduled at 8am but the server is restarted at 8am? Does this mean that the task will not run for that particular day?

If you create it as a web service, then you may run into threading issues (if there are too many users and the background task is running, does this mean  that all the other users will have to suffer in performance whilst this is running?), potential script timeout issues (setting the timeout value to 9999999 seconds is not a solution), application pool recycling issues and so on.

I discovered a NuGet package the other day – Hangfire - http://hangfire.io/ which is a fantastic package for dealing with background tasks, CRON-style scheduled tasks or even tasks to be delayed by a certain time span.

Hangfire integrates with the new Background Work Item API to allow background tasks to run without having to worry about application or server issues that may come along the way compared to traditional methods.

It uses a database backend provider (such as SQL Server) to manage its persistence to ensure that background jobs and scheduled tasks are always run irrespective of what may be happening behind the scenes.

You can enqueue jobs easily with just one line of code:

BackgroundJob.Enqueue(() => AppMailer.RequestQuote(response.Result));

And in addition to this you get a fancy management UI to manage all your tasks:

You also get exception logging, so that you can debug tasks that have failed. Neat!

Hangfire is well documented and a list of all features is available here.