DEV Community

Captain Iminza
Captain Iminza

Posted on

Managing Background Jobs with Hangfire in .NET

What is Hangfire?

Hangfire is an open-source library that allows you to perform background processing in .NET applications. It enables you to create, manage, and monitor jobs efficiently, whether they are one-time tasks or recurring jobs. With Hangfire, you can offload work from the main application thread, ensuring that your application remains responsive.

Getting Started with Hangfire

Installation

To get started, you’ll need to install the Hangfire NuGet package. You can do this via the NuGet Package Manager Console:

dotnet add package Hangfire

Also add sql server package in your project:
dotnet add package Microsoft.Data.SqlClient

Configuration

Once installed, you’ll need to configure Hangfire in your application. This involves setting up Hangfire services and the dashboard, which allows you to monitor your jobs.

In your Startup.cs, add the following:
Make sure to replace "YourConnectionString" with your actual SQL Server connection string.



using Hangfire;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Configure Hangfire to use SQL Server
        services.AddHangfire(x => x.UseSqlServerStorage("Server=your_server;Database=HangfireDB;Trusted_Connection=True;"));
        services.AddHangfireServer();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        // Enable the Hangfire dashboard
        app.UseHangfireDashboard();
        app.UseHangfireServer();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}



Enter fullscreen mode Exit fullscreen mode

Creating Background Jobs

Creating background jobs is straightforward with Hangfire. Here’s an example of how to enqueue a simple job that runs immediately:



public void RunHangFireJob()
{
    BackgroundJob.Enqueue(() => Console.WriteLine("Hello, world!"));
}



Enter fullscreen mode Exit fullscreen mode

This method will be executed in the background as soon as possible.

Recurring Jobs

Hangfire also allows you to schedule recurring jobs. For instance, if you want a job to run every hour, you can use the following code:



public void RunHangfireRecurringJob()
{
    RecurringJob.AddOrUpdate(
        "my-recurring-job",
        () => Console.WriteLine("This job runs every hour"),
        Cron.Hourly);
}



Enter fullscreen mode Exit fullscreen mode

Create a Background Job

Create a new controller to enqueue background jobs. Here’s a simple example:



using Hangfire;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("[controller]")]
public class JobsController : ControllerBase
{
    [HttpPost("enqueue")]
    public IActionResult EnqueueJob()
    {
        // Enqueue a background job
        BackgroundJob.Enqueue(() => Console.WriteLine("Background job executed!"));
        return Ok("Job enqueued!");
    }

    [HttpPost("recurring")]
    public IActionResult ScheduleRecurringJob()
    {
        // Schedule a recurring job
        RecurringJob.AddOrUpdate(
            "my-recurring-job",
            () => Console.WriteLine("This job runs every minute!"),
            Cron.Minutely);

        return Ok("Recurring job scheduled!");
    }
}




Enter fullscreen mode Exit fullscreen mode

Monitoring Jobs

Hangfire comes with a built-in dashboard that provides a user-friendly interface to monitor your jobs. Run your application. You should be able to navigate to http://localhost:5000/hangfire to access the Hangfire dashboard.From here, you can view job status, retry failed jobs, and much more.

Benefits of Using Hangfire

  • Ease of Use: Quick integration into your existing applications.
  • Flexibility: Support for various job types—fire-and-forget, delayed, and recurring jobs.
  • Monitoring: A comprehensive dashboard for managing jobs.
  • Persistent Storage: Jobs can be stored in various backends, including SQL Server and Redis.

Conclusion

Hangfire is a powerful tool for managing background tasks in .NET applications. By allowing you to offload tasks from the main thread, Hangfire helps keep your applications responsive and improves user experience. Whether you need to handle one-time tasks or schedule recurring jobs, Hangfire simplifies the process.

Give Hangfire a try in your next .NET project and experience the ease of background processing!

Top comments (0)