BLogic Systems

Hangfire

Last updated on 

Overview

What is Hangfire?

Hangfire is an open-source framework that helps you to create, process and manage your background jobs, Hangfire supports several kinds of background tasks – short-running and long-running, CPU intensive and I/O intensive, one shot and recurrent. You don’t need to reinvent the wheel – it is ready to use.

Supports

Hangfire works with the majority of .NET platforms: .NET Framework 4.5.1 or later, .NET Core 1.0 or later, or any platform compatible with .NET Standard 1.3. You can integrate it with almost any application framework, including ASP.NET, ASP.NET Core, Console applications, Windows Services, WCF, as well as community-driven frameworks like Nancy or ServiceStack.

How it work?

Hangfire allows you to kick off method calls outside of the request processing pipeline in a very easy, but reliable way. These method invocations are performed in a background thread and called background jobs.

From the 10.000-feet view the library consists of three main components: client, storage and server. Here is a small diagram that describes the main processes in Hangfire:

hangfire-workflow.webp
hangfire-workflow.webp
  1. Hangfire Client: You can create any kind of background jobs. Hangfire does not require you to create special classes. Background jobs are based on regular static or instance methods invocation.
// Using instance
var client = new BackgroundJobClient();
client.Enqueue(() => Console.WriteLine("Easy!"));
client.Delay(() => Console.WriteLine("Reliable!"), TimeSpan.FromDays(1));

// Or Using static
BackgroundJob.Enqueue(() => Console.WriteLine("Hello!"));
  1. Hangfire Storage: Hangfire keeps background jobs and other information that relates to the processing inside a persistent storage (MSSQL, POSTGRES, MYSQL,…). Persistence helps background jobs to survive on application restarts, server reboots, etc. This is the main distinction between performing background jobs using CLR’s Thread Pool and Hangfire.
  2. Hangfire Server: Background jobs are processed by Hangfire Server. It is implemented as a set of dedicated (not thread pool’s) background threads that fetch jobs from a storage and process them. Server is also responsible to keep the storage clean and remove old data automatically. All you need is to create an instance of the BackgroundJobServer class and start the processing
// Using instance
using (new BackgroundJobServer())
{
    Console.WriteLine("Hangfire Server started. Press ENTER to exit...");
    Console.ReadLine();
}

// Or Add the processing server as IHostedService with ASP.NET core
services.AddHangfireServer();

Hangfire uses reliable fetching algorithm for each storage backend, so you can start the processing inside a web application without a risk of losing background jobs on application restarts, process termination and so on.

Job Types Usages

  1. Fire-and-Forget Jobs: Fire-and-forget jobs are executed only once and almost immediately after creation.
var jobId = BackgroundJob.Enqueue(
    () => Console.WriteLine("Fire-and-forget!"));
  1. Recurring Jobs: Recurring jobs fire many times on the specified CRON schedule.
RecurringJob.AddOrUpdate(
    "myrecurringjob",
    () => Console.WriteLine("Recurring!"),
    Cron.Daily);
  1. Delayed Jobs: Delayed jobs are executed only once too, but not immediately, after a certain time interval.
var jobId = BackgroundJob.Schedule(
    () => Console.WriteLine("Delayed!"),
    TimeSpan.FromDays(7));
  1. Continuations: Continuations are executed when its parent job has been finished.
BackgroundJob.ContinueJobWith(
    jobId,
    () => Console.WriteLine("Continuation!"));

ASP.NET Core Application Implementation

Getting Started

I’ll using BLOGICSYSTEMS/BLogicBookingOnlineApi project to guide the implementation. ## Installing Hangfire Hangfire is available as a set of NuGet packages, so you need to add these nuget packages:

<ItemGroup>
  <PackageReference Include="Hangfire.Core" Version="1.8.1"/>
  <PackageReference Include="Hangfire.SqlServer" Version="1.8.1"/>
  <PackageReference Include="Hangfire.AspNetCore" Version="1.8.1"/>
  <PackageReference Include="Microsoft.Data.SqlClient" Version="5.1.1"/>
</ItemGroup>

As you can see from the snippet above, we’ll be using SQL Server as a job storage in this article. Before configuring Hangfire, you’ll need to create a database for it, or use an existing one.

Configuring Settings

Open the appsettings.json file, and add the highlighted lines from the following snippet.

{
  "ConnectionStrings": {
            //Using exists database
        "DBConnectionString": "data source=.;Initial Catalog=BLogicPOS9;Database=BLOGICPOS9;User Id=sa;Password=****;MultipleActiveResultSets=True;Connect Timeout=300;TrustServerCertificate=true;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      //Config Log level
      "Hangfire": "Information"
    }
  }
}

Registering Services

After updating the application settings, open the Program.cs file, we need to import the Hangfire namespace.

using Hangfire;
using Hangfire.Dashboard;

Dependency Injection is one of the primary techniques introduced in ASP.NET Core. The Hangfire.AspNetCore integration package adds an extension method to register all the services, their implementation, as well as logging and a job activator. As a parameter, it takes an action that allows to configure Hangfire itself.

// Add Hangfire services
builder.Services.AddHangfire(configuration => configuration
        .SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
        .UseSimpleAssemblyNameTypeSerializer()
        .UseRecommendedSerializerSettings()
        .UseSqlServerStorage(builder.Configuration.GetConnectionString("DBConnectionString")));

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

Adding Dashboard UI

After registering Hangfire types, you can now choose features you need to add to your application. The following snippet shows you how to add the Dashboard UI to use all the Hangfire features immediately. The following lines are fully optional, and you can remove them completely, if your application will only create background jobs, as separate application will process them.

// Enable Dashboard feautre
app.UseHangfireDashboard();

// Map Dashboard endpoint
app.MapHangfireDashboard("/hangfire");

Make Sure HangFire Working

After finish setup, let’s do some test to make sure it working Open HomeController.cs adding lines of code

[HttpGet("ping")]
public string Get()
{
    var jobId = BackgroundJob.Enqueue(() => testHangFire());
    return "pong";
}

public void testHangFire()
{
    System.Console.WriteLine("Hi there Blogic");
}

Open web browser go to http://localhost/api/home/ping. Then check your console it should print Hi there Blogic.

You can go to dashboard by url http://localhost/hangfire to manage those jobs.