An Introduction to Hangfire Integration in.NET 8

Leave a Comment

An open-source library called Hangfire is used in.NET applications to process jobs in the background. It enables you to carry out lengthy operations, such processing photos, sending emails, or any other work, asynchronously without interfering with the main request thread. Hangfire manages job persistence, retries, and scheduling to maintain the responsiveness of your application while guaranteeing the reliable execution of crucial background operations. 

Hangfire supports several types of jobs.

  • Fire-and-Forget Jobs: Executed only once immediately after creation.
  • Delayed Jobs: Scheduled to run after a specified delay.
  • Recurring Jobs: Run according to a defined schedule (e.g., every day at a particular time).
  • Continuation Jobs: Triggered when their parent job completes.

Prerequisites

Before you begin, ensure you have,

  • .NET 8 SDK installed.
  • A code editor (Visual Studio or VS Code).
  • SQL Server or LocalDB for job storage.
  • Basic knowledge of C# and ASP.NET Core.
Setting Up the Sample Project

1. Create a New Minimal API Project

Open your terminal.

dotnet new web -n HangfireSample

2. Add Hangfire NuGet Packages

Navigate to your project folder and run.

cd HangfireSample
dotnet add package Hangfire.AspNetCore
dotnet add package Hangfire.SqlServer
dotnet add Microsoft.Data.SqlClient

3. Configure the Database

Update appsettings.json with your connection string. For example, using LocalDB.

{
  "ConnectionStrings": {
    "HangfireConnection": "Server=Instance;Database=Your_DB;Integrated Security=True;TrustServerCertificate=true;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}

Hangfire will automatically create the necessary tables.

Implementing Hangfire in .NET 8

Replace the contents of Program.cs with the following code.

using Hangfire;
using Hangfire.SqlServer;

var builder = WebApplication.CreateBuilder(args);

// Configure Hangfire to use SQL Server storage.
builder.Services.AddHangfire(config =>
{
    config.UseSqlServerStorage(builder.Configuration.GetConnectionString("HangfireConnection"));
});

// Start the Hangfire Server to process background jobs.
builder.Services.AddHangfireServer();

// (Optional) Add Swagger for API testing.
builder.Services.AddEndpointsApiExplorer();

var app = builder.Build();

// Use Swagger UI in development mode.
// Expose the Hangfire Dashboard at /hangfire (be sure to secure this in production).
app.UseHangfireDashboard();

// Root endpoint to test basic connectivity.
app.MapGet("/", () => "Hello World from .NET 8 and Hangfire!");

// Endpoint to enqueue a fire-and-forget job.
app.MapGet("/enqueue", (IBackgroundJobClient backgroundJobs) =>
{
    backgroundJobs.Enqueue(() => Console.WriteLine("Hangfire Fire-and-Forget Job executed!"));
    return Results.Ok("Background job has been enqueued.");
});
// New endpoint to schedule a delayed job (executes after 1 minute).
app.MapGet("/schedule", (IBackgroundJobClient backgroundJobs) =>
{
    backgroundJobs.Schedule(
        () => Console.WriteLine("Delayed Hangfire Job executed after 1 minute!"),
        TimeSpan.FromMinutes(1)
    );
    return Results.Ok("Delayed job scheduled to run after 1 minute.");
});

// Run the application.
app.Run();
How does This Work?

Hangfire Configuration

  • AddHangfire registers Hangfire with SQL Server storage using the provided connection string.
  • AddHangfireServer starts a background server to process the queued jobs.

Endpoints

  • Root ("/"): Returns a basic welcome message.
  • Enqueue ("/enqueue"): Uses BackgroundJob.Enqueue to immediately queue a fire-and-forget job.
  • Schedule ("/schedule"): Uses BackgroundJob.Schedule to queue a job that will execute after a 1-minute delay.
  • Hangfire Dashboard: Accessible at /hangfire, it provides real-time monitoring of job statuses (enqueued, processing, succeeded, or failed).
Visual Overview

Architecture Diagram

+-----------------------------+
|           Client           |
|   (Browser, Postman, etc.) |
+--------------+-------------+
               |
           HTTP Request
               |
               v
+-----------------------------+
|       .NET 8 Minimal API    |
| Endpoints:                 |
|   "/"         -> Hello World|
|   "/enqueue"  -> Enqueue    |
|   "/schedule" -> Delay      |
+--------------+-------------+
               |
     Enqueue / Schedule Command
               |
               v
+-----------------------------+
|   Hangfire Storage (SQL DB) |
+--------------+-------------+
               |
     Hangfire Server Polls
               |
               v
+-----------------------------+
| Hangfire Background Job     |
|        Processor            |
+-----------------------------+

Step-by-Step Flow

  • Client Interaction: A client calls /enqueues, or /schedules to add jobs.
  • Job Storage: Hangfire persists the job details in SQL Server.
  • Job Processing: The Hangfire server continuously polls the queue and executes ready jobs.
  • Dashboard Monitoring: The Hangfire Dashboard lets you view job states and monitor execution.

Key Terms Explained

  • Fire-and-Forget Job (Enqueue): Enqueued tasks that run as soon as they’re picked up. Ideal for operations that don't require an immediate response.
  • Delayed Job (Schedule): Tasks that start after a delay—useful for follow-up operations like sending reminders.
  • Background Job: Any task executed asynchronously outside the main HTTP request/response cycle.
  • Hangfire Server: A service that retrieves and executes background jobs from storage.
  • Hangfire Dashboard: A web-based UI for monitoring job statuses. For production, secure this dashboard with proper authentication.

Running and Testing

Start the Application

dotnet run

Test the Endpoints

  • Root: Navigate to http://localhost:5000/ to see "Hello World from .NET 8 and Hangfire!"
  • Enqueue: Visit http://localhost:5000/enqueue to dispatch a fire-and-forget job.
  • Schedule: Visit http://localhost:5000/schedule to schedule a job for execution after one minute.
  • Dashboard: Open http://localhost:5000/hangfire to monitor jobs in real time.

Output Samples

Conclusion
This tutorial covered both immediate (enqueue) and delayed (schedule) job processing, showing how to incorporate Hangfire into a.NET 8 Minimal API project. Long-running processes can be transferred to background jobs to maintain the scalability and responsiveness of your application.

Then, to enhance your background processing capabilities, think about investigating repeating jobs, job continuations, or including bespoke error handling.

Have fun with your coding!

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Previous PostOlder Post Home

0 comments:

Post a Comment