Joydip Kanjilal
Contributor

How to work with Hangfire in C#

opinion
Apr 01, 20164 mins
Open SourceSoftware DevelopmentWeb Development

Take advantage of Hangfire, an open source job scheduling framework, to schedule fire-and-forget, recurring tasks in Web applications sans the need of a Windows Service

Scheduling jobs in Web applications is a challenge, and you can choose from many frameworks for the task. A popular open source library, Hangfire is one framework that can be used for scheduling background jobs in .Net.

Why should I use Hangfire?

There are many job scheduling frameworks available today. Why then should you use Hangfire instead of, say, Quartz.Net, which is another popular framework that has long been in use? Well, one of the major drawbacks of Quartz.Net is that it needs a Windows Service. On the contrary, you don’t need a Windows Service to use Hangfire in your application. The ability to run without a Windows Service makes Hangfire a good choice over Quartz.Net. Hangfire takes advantage of the request processing pipeline of ASP.Net for processing and executing jobs.

Note that Hangfire is not limited to Web applications; you can also use it in your Console applications. The documentation for Hangfire is very detailed and well structured, and the best feature is its built-in dashboard. The Hangfire dashboard shows detailed information on jobs, queues, status of jobs, and so on.

Getting started

To create a new project in Visual Studio that leverages Hangfire, follow these steps:

  1. Open Visual Studio 2015
  2. Click on File > New > Project
  3. Select Visual C# > Web from the list of the project templates displayed
  4. Select ASP.Net Web application from the list of the Web project templates
  5. Save the project with a name

The next step is installing and configuring Hangfire in your application; the process is quite straightforward. You can install Hangfire via the NuGet Package Manager in Visual Studio. Alternatively, you can also use the Package Manager Console to install the Hangfire library. The default installation of Hangfire uses SQL Server for storing scheduling information. Additionally, you can install Hangfire.Redis if you use Redis instead for storage.

Note that Hangfire stores your jobs in a persistent storage — you need to configure the storage before you start using Hangfire. To do this, create a database and specify the database credentials in the connection string in the configuration file. You don’t need to create the tables in your database; Hangfire will do that for you automatically. We will see how and when it will be done later.

Now that the database has been created and the connection string information specified in the configuration file of the application, the next step is to modify the Startup.cs file and provide the necessary connection string information. The following code listing illustrates how the Startup.cs file looks after the configuration details have been specified.

using Hangfire;

using Microsoft.Owin;

using Owin;

using System;

[assembly: OwinStartupAttribute(typeof(HangFire.Startup))]

namespace HangFire

{

    public partial class Startup

    {

        public void Configuration(IAppBuilder app)

        {

            ConfigureAuth(app);

            GlobalConfiguration.Configuration

                .UseSqlServerStorage("DefaultConnection");

            BackgroundJob.Enqueue(() => Console.WriteLine("Getting Started with HangFire!"));

            app.UseHangfireDashboard();

            app.UseHangfireServer();

        }

    }

}

You’re all set. When you run the application and suffix the URL with “/hangfire”, you can see the Hangfire dashboard. When you execute this the very first time, a new table is created in the database. The tables that are created include AggregatedCounter, Counter, Hash, Job, JobParameter, JobQueue, List, Schema, Server, Set, and State. Creating a fire-and-forget background in Hangfire is quite simple. You can create a background job using the Enqueue() method of the BackgroundJob class. Here’s an example:

BackgroundJob.Enqueue(() => Console.WriteLine("This is a fire-and-forget job that would run in the background."));

A delayed background job is one that waits (for the delay interval), then executes much the same way as a normal fire-and-forget background job. The following code snippet illustrates how you can create a delayed background job using the Schedule() method of the BackgroundJob class.

BackgroundJob.Schedule(() => Console.WriteLine("This background job would execute after a delay."), TimeSpan.FromMilliseconds(1000));

If you were to execute jobs that would execute after a specific interval of time, you would need to create recurring jobs in Hangfire. To create a recurring job, you would have to leverage the RecurringJob class. Note that you can also specify “cron” expressions when scheduling jobs in Hangfire. The following code snippet illustrates how you can create a recurring job using the Hangfire library.

RecurringJob.AddOrUpdate(() => Console.WriteLine("This job will execute once in every minute"), Cron.Minutely);

Check out the Hangfire Highlighter tutorial for more information.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author