.NET  

How to Run Background Jobs in .NET Using Hangfire

Introduction

In real-world applications, not every task should run immediately while the user is waiting. Some tasks take time and can slow down your application if executed directly.

For example:

  • Sending emails

  • Generating reports

  • Processing payments

  • Running scheduled tasks

This is where background jobs come in.

Hangfire is one of the most popular libraries in .NET that allows you to run background jobs easily and reliably.

In this guide, you will learn what background jobs are, why they are important, and how to implement them using Hangfire in a simple and practical way.

What are Background Jobs?

Background jobs are tasks that run in the background without blocking the main application.

Instead of making the user wait, the task runs separately.

In simple words:
Background jobs help your application stay fast by handling heavy work in the background.

What is Hangfire?

Hangfire is a library for .NET that allows you to schedule and run background jobs.

It provides:

  • Easy job scheduling

  • Automatic retries

  • Dashboard for monitoring

  • Persistent storage (jobs are saved in database)

In simple words:
Hangfire helps you run tasks in the background without losing them.

Why Use Hangfire?

  • Improves application performance

  • Handles long-running tasks

  • Reliable job execution

  • Built-in dashboard for monitoring

Types of Background Jobs in Hangfire

Hangfire supports multiple types of jobs:

  1. Fire-and-Forget

    • Runs once immediately

  2. Delayed Jobs

    • Runs after a specific time

  3. Recurring Jobs

    • Runs on schedule (like daily, weekly)

  4. Continuations

    • Runs after another job completes

Step-by-Step: Implement Hangfire in ASP.NET Core

Step 1: Create a .NET Project

dotnet new webapi -n HangfireDemo
cd HangfireDemo

Step 2: Install Hangfire Packages

dotnet add package Hangfire
dotnet add package Hangfire.AspNetCore

Step 3: Configure Hangfire in Program.cs

builder.Services.AddHangfire(config =>
    config.UseInMemoryStorage());

builder.Services.AddHangfireServer();

Step 4: Enable Hangfire Dashboard

app.UseHangfireDashboard();

Now you can access dashboard at:

http://localhost:5000/hangfire

Step 5: Create a Background Job

public class EmailService
{
    public void SendEmail()
    {
        Console.WriteLine("Email sent successfully");
    }
}

Step 6: Trigger Background Job

BackgroundJob.Enqueue<EmailService>(x => x.SendEmail());

This runs the job immediately in background.

Step 7: Create Delayed Job

BackgroundJob.Schedule<EmailService>(x => x.SendEmail(), TimeSpan.FromMinutes(10));

This runs after 10 minutes.

Step 8: Create Recurring Job

RecurringJob.AddOrUpdate<EmailService>(
    "daily-email",
    x => x.SendEmail(),
    Cron.Daily);

This runs daily automatically.

Step 9: Monitor Jobs in Dashboard

Hangfire dashboard shows:

  • Job status

  • Success/failure

  • Execution history

This helps you track everything easily.

Best Practices for Using Hangfire

  • Use persistent storage (SQL Server, Redis)

  • Avoid heavy logic inside jobs

  • Handle exceptions properly

  • Use retry policies

Real-World Use Cases

  • Sending emails after user registration

  • Generating invoices

  • Data processing tasks

  • Scheduled reports

Difference Between Background Jobs vs Synchronous Tasks

FeatureSynchronousBackground Jobs
ExecutionImmediateAsync
User WaitYesNo
PerformanceSlowerFaster

Conclusion

Hangfire is a powerful and easy-to-use tool for handling background jobs in .NET applications. It helps improve performance, reliability, and user experience.

By moving heavy tasks to the background, you can build faster and more scalable applications.