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:

Add Hangfire packages

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

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;"


"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": "*"

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
    .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

// Add framework services.
ConfigureServices method with sample code

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

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:


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:

        () => Console.WriteLine("Recurring job!"),

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

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:

        () => Console.WriteLine("Recurring job2"),
    "*/15 * * * *");

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

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:

For ASP.NET Core applications (I mainly used this):

Hangfire home page:

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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: