Background automation tasks in .NET Core – sample web application using Hangfire

It is the second post about Hangfire, but this time I am using Hangfire in web application. And there is link to previous post about Hanfire in console application:
Background automation tasks in .NET – sample console application using Hangfire

I will show a simple web application using Hangfire to automate tasks.

First, create a new project: ASP.NET Core Web App (MVC). In my case netcoreapp3.1:

Create a new project – ASP.NET Core Application

Install Hangfire – add packages:
Hangfire.Core
Hangfire.SqlServer
Hangfire.AspNetCore

Add Hangfire packages

Next step, create a database. Go to SSMS and execute the command:

CREATE DATABASE [HangfireWebApp]
GO
Create HangfireWebApp database in SSMS

Afterwards changes to appsettings.json file. We need to add HangfireConnection string and Hangfire logging config.
You need to take attention on connection string. Put appropriate data source for your local database and appropriate database name, same like created in sql command to create database.

My connection string:

"HangfireConnection": "Data Source=(LocalDb)\\MSSQLLocalDB; Database=HangfireWebApp; Integrated Security=True;"

Logging:

"Hangfire": "Information"

All appsettings.json code:

{
  "ConnectionStrings": {
    "HangfireConnection": "Data Source=(LocalDb)\\MSSQLLocalDB; Database=HangfireWebApp; Integrated Security=True;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information",
      "Hangfire": "Information"
    }
  },
  "AllowedHosts": "*"
}
appsettings.json

Now go to the Startup.cs file and import Hangfire namespaces:

using Hangfire;
using Hangfire.SqlServer;
Add Hangfire namespaces

Subsequently, add Hangfire services in Startup.cs.
Copy the following code to the ConfigureServices method:

// Add Hangfire services.
services.AddHangfire(configuration => configuration
    .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
    .UseSimpleAssemblyNameTypeSerializer()
    .UseRecommendedSerializerSettings()
    .UseSqlServerStorage(Configuration.GetConnectionString("HangfireConnection"), new SqlServerStorageOptions
    {
        CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
        SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
        QueuePollInterval = TimeSpan.Zero,
        UseRecommendedIsolationLevel = true,
        DisableGlobalLocks = true
    }));

// Add the processing server as IHostedService
services.AddHangfireServer();

// Add framework services.
services.AddMvc();
ConfigureServices method with sample code

Then we can add Dashboard UI (optional) in Configure method:

app.UseHangfireDashboard();
Dashboard UI, Configure method

And finally add sample background job, also in Configure method:

Inject IBackgroundJobClient:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IBackgroundJobClient backgroundJobs)

And add this line of code with background job (executed only once):

backgroundJobs.Enqueue(() => Console.WriteLine("Hangfire!"));
Configure method, IBackgroundJobClient and background job

Now we can run our application. Output messages:

Hangfire output – web app
Background job output

As we can see, there are “SQL objects installed”, “Starting Hangfire Server” messages and one message from the background job appear. For now, I have one task (with Console.WriteLine) that writes: “Hangfire!”.

Database tables have also been created that store all data related to Hangfire:

Hangfire database with tables

When the application has started, we can open Dashboard, just add “/hangfire” to URL. In my case “Successfully registered URL “https://localhost:44308/”, so full URL for dashboard:

https://localhost:44308/hangfire

On Jobs -> Succeeded tab we can check succeeded jobs:

Succeeded Jobs
Succeeded Job – details

Now we can try to add one more task that run recurring job. Just add these lines of code:

RecurringJob.AddOrUpdate(
        () => Console.WriteLine("Recurring job!"),
    Cron.Minutely);
RecurringJob

And every minute it displays: “Recurring job!”. We can configure the time period in the Cron expression, in this sample it is Cron.Minutely.

RecurringJob
Recurring jobs dashboard

As I described in my previous blog post about Hangfire (Background automation tasks in .NET Core – sample console application using Hangfire) – we can also use cron expressions to specify a more complex schedule. For example, run every 15th minute:

RecurringJob.AddOrUpdate("id-job2",
        () => Console.WriteLine("Recurring job2"),
    "*/15 * * * *");

Cron expression that I used: “*/15 * * * *”, I like this site for generating cron expressions:
https://crontab.guru

Also, I had to add a recurring job id in method AddOrUpdate: “id-job2”, because identifiers should be unique for each recurring job.

Recurring jobs, dashboard – 2 items

And that’s it, I recommend this documentation for Hangfire:
https://docs.hangfire.io/en/latest/

For ASP.NET Core applications (I mainly used this):
https://docs.hangfire.io/en/latest/getting-started/aspnet-core-applications.html

Hangfire home page:
https://www.hangfire.io

In the next post, I will show how to call (reccuring) a controller method in Hangfire.

Leave a comment