Overview

Why Hangfire is required in Background Processing

So, these are things which we are able to do periodically over a certain period of time as per our requirement.

Prerequisites

Agenda

There are different types of jobs that are present in the Hangfire. We will look at that one by one

There are also two jobs present now in Hangfire one is Batch Job and another is Batch Continuation but these are present in the Hangfire Pro version and which are used to execute multiple jobs in batch as a single entity.

Step 1

Open Visual Studio 2022 and create a new .NET Core Web API Project

Step 2

Provide the Project name HangfireDemo and then provide the location

Step 3

Also, provide additional information like .NET Framework 6, Configure HTTPS and enable Open API support and swagger

Step 4

Install Hangfire NuGet Package.

Step 5

Create API Controller and name it as ProductController

using Hangfire;
using Microsoft.AspNetCore.Mvc;

namespace HangfireDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        [HttpGet]
        [Route("login")]
        public String Login()
        {
            //Fire - and - Forget Job - this job is executed only once
            var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("Welcome to Shopping World!"));

            return $"Job ID: {jobId}. Welcome mail sent to the user!";
        }

        [HttpGet]
        [Route("productcheckout")]
        public String CheckoutProduct()
        {
            //Delayed Job - this job executed only once but not immedietly after some time.
            var jobId = BackgroundJob.Schedule(() => Console.WriteLine("You checkout new product into your checklist!"),TimeSpan.FromSeconds(20));

            return $"Job ID: {jobId}. You added one product into your checklist successfully!";
        }

        [HttpGet]
        [Route("productpayment")]
        public String ProductPayment()
        {
            //Fire and Forget Job - this job is executed only once
            var parentjobId = BackgroundJob.Enqueue(() => Console.WriteLine("You have done your payment suceessfully!"));

            //Continuations Job - this job executed when its parent job is executed.
            BackgroundJob.ContinueJobWith(parentjobId, () => Console.WriteLine("Product receipt sent!"));

            return "You have done payment and receipt sent on your mail id!";
        }

        [HttpGet]
        [Route("dailyoffers")]
        public String DailyOffers()
        {
            //Recurring Job - this job is executed many times on the specified cron schedule
            RecurringJob.AddOrUpdate(() => Console.WriteLine("Sent similar product offer and suuggestions"), Cron.Daily);

            return "offer sent!";
        }
    }
}

Step 6

Finally, let’s configure things in Program.cs Class related to Hangfire like SQL Server Database and middleware which we need.

using Hangfire;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

//Hangfire
builder.Services.AddHangfire(x => x.UseSqlServerStorage(@"Data Source=DESKTOP-8RL8JOG;Initial Catalog=hangfire;Integrated Security=True;Pooling=False"));
builder.Services.AddHangfireServer();

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseHangfireDashboard();

app.UseAuthorization();

app.MapControllers();

app.Run();

So here we register a few things related to Hangfire and SQL Server Database.

Step 7

Now, after you run the application, this swagger window will open, and using this we will perform operations one by one after hitting API endpoints.

Also, it will create the following tables in the database related to Hangfire to manage jobs.

Step 8

You can now also open the Hangfire dashboard to manage background running jobs after hitting

The same API port in another window https://localhost:7204/hangfire

Now we are going to execute API endpoints one by one and check newly created jobs in the Hangfire dashboard.

First we hit the login endpoint from swagger UI. Then it will create one job and execute that job immediately as shown in the below images

Here, in Hangfire Dashboard you can see all the details about jobs like succeeded, scheduled, failed, and processing as I have shown in the above images.

Now we hit another endpoint productcheckout and it will schedule one background job and execute once after a specified time interval

After this we are going to hit the third endpoint which is to create a continuation job and execute. After this its parent job will get executed as shown in the image. Here first parent job is to execute and after that immediate child job which is the continuation job is executed.

Finally, we are going to hit our last API endpoint and check how recurring job is executed one by one.

Here you can see how recurring job is created and executed one by one after a specific time interval.

So, this is all about Hangfire which we used in .NET Core to schedule background jobs as per our requirements.

I hope you now understand a few things related to Hangfire

Happy Coding!