DEV Community

Jawad Hayat
Jawad Hayat

Posted on

Implementing Hangfire in .NET: A Beginner's Guide

Introduction
Recently, I delved into the world of Hangfire, an open-source library that simplifies the process of scheduling and executing background tasks in .NET applications. Hangfire allows developers to run tasks in the background, ensuring that the main application remains responsive and efficient. In this post, I’ll share my experience and provide a step-by-step guide on implementing Hangfire in your .NET projects.

What is Hangfire?
Hangfire is a .NET library that provides a simple and reliable way to perform background processing in your applications. It offers features like:

Background task processing
Delayed and recurring jobs
Monitoring and dashboard capabilities

Step 1: Install Hangfire

Install-Package Hangfire
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure Hangfire

builder.Services.AddHangfire(config =>
{
    config.UseSqlServerStorage(builder.Configuration.GetConnectionString("DefaultConnection")); // Use your preferred storage here
});
builder.Services.AddHangfireServer();


// Map Hangfire Dashboard
app.UseHangfireDashboard();
Enter fullscreen mode Exit fullscreen mode

Step 3: Creating Background Jobs

[HttpGet]
[Route("FireAndForgetJob")]
public ActionResult CreateFireAndForgetJob()
{
    BackgroundJob.Enqueue<TestJob>(x => x.WriteLog("Fire-and-Forget Job"));
    //BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-Forget Job"));
    return Ok();
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Delayed and Recurring Jobs

[HttpGet]
[Route("DelayJob")]
public ActionResult CreateDelayJob()
{
    var scheduleDateTime = DateTime.UtcNow.AddSeconds(5);
    var dateTimeOffset = new DateTimeOffset(scheduleDateTime);
    BackgroundJob.Schedule<TestJob>(x => x.WriteLog("Delay-and-Schedule Job"), dateTimeOffset);
    //BackgroundJob.Schedule(() => Console.WriteLine("Delay-and-Schedule Job"),dateTimeOffset);
    return Ok();
}
[HttpGet]
[Route("ContinuationJob")]
public ActionResult CreateContinuationJob()
{
    var scheduleDateTime = DateTime.UtcNow.AddSeconds(5);
    var dateTimeOffset = new DateTimeOffset(scheduleDateTime);
    var jobID = BackgroundJob.Schedule<TestJob>(x => x.WriteLog("Delay-and-Schedule 2nd Job"), dateTimeOffset);
    //var jobID = BackgroundJob.Schedule(() => Console.WriteLine("Delay-and-Schedule 2nd Job"), dateTimeOffset);

    var job2ID = BackgroundJob.ContinueJobWith<TestJob>(jobID, x => x.WriteLog("ContinuationJob1 triggered"));
    var job3ID = BackgroundJob.ContinueJobWith<TestJob>(job2ID, x => x.WriteLog("ContinuationJob2 triggered"));
    var job4ID = BackgroundJob.ContinueJobWith<TestJob>(job3ID, x => x.WriteLog("ContinuationJob3 triggered"));
    return Ok();
}
[HttpGet]
[Route("RecurringJob")]
public ActionResult CreateRecurringJob()
{
    RecurringJob.AddOrUpdate<TestJob>("RecurringJob1", x => x.WriteLog("RecurringJob triggered"), "* * * * *");
    return Ok();
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Monitoring Jobs
Hangfire comes with a built-in dashboard that allows you to monitor the status of your background jobs. You can access the dashboard by navigating to /hangfire in your browser.

Conclusion
Hangfire makes it incredibly easy to add background processing to your .NET applications. Its simplicity and powerful features can significantly enhance the performance and responsiveness of your applications. By following the steps outlined in this guide, you can quickly get started with Hangfire and start leveraging its capabilities in your projects.

Top comments (1)

Collapse
 
farzan_ansari_af9fce3d05c profile image
Farzan Ansari

Explained well.