Simple System Tasks with MVC

A common requirement in web applications is the ability to run one or more recurring tasks on a specified schedule. Previously this involved either managing background jobs within the application or setting up windows services to run using scheduled tasks. Hangfire is an open source solution for running system tasks and is surprisingly easy to get up and running.

Hangfire can be installed using nuget into your application

PM> Install-Package Hangfire

Hangfire needs to be backed by a data store to allow jobs to be queued. If you are already using SQL Server for your application then all you need to do is tell Hangfire the connection string to use. This can be done in the Startup.cs Configuration method like so:

GlobalConfiguration.Configuration.UseSqlServerStorage("MyConnection");

For hangfire to run jobs you need to also spin up a server this again is a single line in the Startup.cs confguration:

app.UseHangfireServer();

On first run of the application hangfire will check and create the db table structure using the connection string provided. You will need to ensure that either sufficient permissions are given or run the application locally to create the table structure prior to actual deployment.

For the sake of simplicity imagine you have a static method somewhere to run a more complex operation:

public static class MyRecurringJobs 
{
    public static void DailyJob()
    {
        // Do Stuff
    }
}

To register the job with Hangfire add the following line in the Startup.cs configuration method. This example will trigger the above method every day at 9 PM.

RecurringJob.AddOrUpdate(() => MyRecurringJobs.DailyJob(), Cron.Daily(21));

By default Hangfire will automatically retry failed jobs a number of times which may not be the desired behavior depending on your application. Again this is really easy to change using a data attribute. You can specify the retry attempts on an individual method or apply a global filter, if you specify 0 as the retry attempt number then the job will not retry if it fails.

[AutomaticRetry(Attempts = 0)]

Hangfire also come with a really handy dashboard to help manage things, this is optional but equally easy to set-up all you need to do is register the dashboard in your startup.cs

app.UseHangfireDashboard();

The dashboard will only be available from local connections but it can be set-up as an authenticated page on your site should you need that capability.