Background Job Processing with Hangfire

Niraj Ranasinghe
4 min readSep 17, 2023

--

In today’s digital landscape, making applications responsive is key. Whether you’re working on a website, e-commerce platform, or web app, handling background tasks efficiently is a must. Meet Hangfire, a user-friendly open-source library for .NET that makes background job processing a breeze. In this article, we’ll explore Hangfire’s core features, job types, and walk you through examples to get you started.

Photo by Levi Loot on Unsplash

What is Hangfire?

Hangfire is a .NET library that simplifies background job processing. It offers an easy-to-use and dependable solution for scheduling, enqueuing, and managing background tasks in your applications.

Key Features of Hangfire

  1. Simple API: Hangfire provides a straightforward API, making it simple to add background tasks to your application. These tasks could be anything from sending emails to processing data without complicating your code.
  2. Scheduled Jobs: Hangfire lets you schedule jobs at specific times or intervals. Need to send daily newsletters or generate weekly reports? Hangfire’s got you covered.
  3. Dashboard: Hangfire comes with a built-in dashboard for real-time job monitoring. Track job history, view statistics, and retry failed tasks from this user-friendly interface.
  4. Extensibility: Hangfire is highly customizable. You can create custom job filters, storage providers, and more to tailor it to your application’s unique needs.
  5. Support for Multiple Storage Providers: Hangfire is compatible with various storage providers, including SQL Server and Redis. Choose the storage solution that fits your application best.

Types of Background Jobs

Fire-and-Forget Jobs

Fire-and-forget jobs are used when you want to perform a task in the background without waiting for a result. These jobs are enqueued and executed asynchronously.

Example: Sending a welcome email to a new user.

BackgroundJob.Enqueue(() => EmailService.SendWelcomeEmail(newUser));

Delayed Jobs

Delayed jobs allow you to schedule a task to run after a specified time delay. This is useful for tasks that should be executed sometime in the future.

Example: Sending a reminder to a user 24 hours after they registered.

BackgroundJob.Schedule(() => ReminderService.SendReminder(user), TimeSpan.FromHours(24));

Recurring Jobs

Recurring jobs are used for tasks that need to run periodically at fixed intervals. You can specify a cron expression or a time interval for these jobs.

Example: Updating product prices every day at midnight.

RecurringJob.AddOrUpdate(() => PriceService.UpdateProductPrices(), Cron.Daily);

Benefits of Using Hangfire

  1. Reliability: Hangfire ensures your background jobs run reliably, even if your application restarts or crashes. This reliability is crucial for tasks like processing payments or sending critical notifications.
  2. Improved Responsiveness: By offloading time-consuming tasks to the background, Hangfire keeps your application responsive. Users won’t face delays or timeouts due to resource-intensive operations.
  3. Scalability: As your application grows, you can scale background job processing by adding more servers or using distributed storage solutions like Redis.

Getting Started with Hangfire

  1. Install Hangfire: Add the Hangfire.Core package to your project using NuGet.
  2. Configuration: Configure Hangfire with your chosen storage provider, specifying connection strings and settings.
  3. Create Jobs: Define the background jobs you want to execute.
  4. Enqueue Jobs: Use Hangfire’s API to enqueue your background jobs. You can schedule jobs or queue them for immediate execution.
  5. Monitor and Manage: Keep an eye on your background jobs using Hangfire’s dashboard. You can also manage and retry failed jobs from here.

Required Configuration

Program.cs

using Hangfire;
using Hangfire.Shared.Jobs;
using HangfireBasicAuthenticationFilter;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddHangfire(opt =>
{
opt.UseSqlServerStorage(builder.Configuration.GetConnectionString("DefaultConnectionString"))
.SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings();
});

var app = builder.Build();

app.UseSwagger();
app.UseSwaggerUI();

app.UseHttpsRedirection();

app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
Authorization = new[]
{
new HangfireCustomBasicAuthenticationFilter
{
User = app.Configuration.GetSection("HangfireSettings:Username").Value,
Pass = app.Configuration.GetSection("HangfireSettings:Password").Value
}
}
});

RecurringJob.AddOrUpdate<ISendEmail>(Guid.NewGuid().ToString(),
x => x.Execute(), Cron.Hourly);

app.UseAuthorization();

app.MapControllers();

app.Run();

Setting up Hangfire:

  • builder.Services.AddHangfire(opt => {...}): This section configures Hangfire in the application's service collection. It specifies that Hangfire should use SQL Server as the storage backend, sets data compatibility level, and configures serialization settings.

Configuring Hangfire Dashboard:

  • app.UseHangfireDashboard("/hangfire", new DashboardOptions {...}): This sets up the Hangfire Dashboard, which provides a web-based interface for monitoring and managing background jobs. It is configured to be accessible at the "/hangfire" URL.
  • Authorization is configured for the Hangfire Dashboard. Only users with valid credentials will be able to access it. Basic authentication is employed here, and the username and password are retrieved from the application's configuration settings.

Scheduling a Recurring Job:

  • RecurringJob.AddOrUpdate<ISendEmailJob>(...): This line schedules a recurring job using Hangfire. The job is of type ISendEmailJob, and it is scheduled to execute the Execute method at a specific interval defined by the Cron.Minutely expression, which means it will run every minute.

Running the Application:

  • app.Run(): This starts the application and makes it listen for incoming HTTP requests.

Conclusion

Hangfire is an excellent tool for simplifying background job processing in .NET applications. With its straightforward API, reliability, and extensibility, Hangfire empowers you to build responsive and scalable applications. Whether you’re working on a small website or a large-scale enterprise app, Hangfire ensures your background tasks are managed effortlessly.

I want to express my gratitude to the helpful AI tools that have contributed to improving the accuracy and quality of this article. I hope you’ve gained valuable insights from reading it. Your interest and support mean a lot to me, and I look forward to sharing more exciting content with you in the future.

Keep an eye out for my upcoming articles, and until then, happy coding!

--

--

Niraj Ranasinghe

I love sharing insights on Software Development, Emerging Tech, and Industry Trends. Join me on my journey to explore the exciting World of Technology!