What is Hangfire and why is it needed?
\n\nHangfire is a powerful and popular library for C# (.NET) designed for executing background jobs. In modern web development, there is often a need to perform operations that should not block the main execution thread of the application. For example: sending email notifications, generating reports, processing uploaded files, synchronizing data with external APIs, cleaning up outdated database records, and much more.
\n\nHangfire provides a simple yet flexible way to run such tasks. Key features of the library:
\n- \n
- Background job execution: Tasks run asynchronously without blocking the user response. \n
- Scheduling: You can run tasks on a schedule (cron expressions) or with a delay. \n
- Reliability: Hangfire stores job information in persistent storage (database). Even if the application restarts, unfinished jobs will be executed. \n
- Monitoring: Built-in web interface (Dashboard) allows you to track job status, view logs, and retry failed jobs. \n
- Retries: If a job fails with an error, Hangfire automatically attempts to execute it again (with a configurable retry policy). \n
- DI Integration: Easily integrates with Dependency Injection containers in ASP.NET Core. \n
Hangfire supports various storage options: SQL Server, PostgreSQL, Redis, MongoDB, and others. This makes it suitable for projects of any scale — from small websites to high-load enterprise systems.
\n\nInstallation
\n\nHangfire is installed via NuGet Package Manager. Unlike Python, where pip install is used, the .NET ecosystem uses dotnet add package or the Visual Studio package manager.
To install the base Hangfire package, run the following command in the terminal (in your project's root folder):
\n\ndotnet add package Hangfire\n\nThis command installs the Hangfire core and dependencies for in-memory job storage (InMemory). For a production environment, you will need to install a package for a specific database, for example:
\n\n- \n
- SQL Server:
dotnet add package Hangfire.SqlServer\n - PostgreSQL:
dotnet add package Hangfire.PostgreSql\n - Redis:
dotnet add package Hangfire.Redis\n
After installing the packages, you need to configure Hangfire in the Program.cs file (for ASP.NET Core) or Startup.cs.
Quick Start
\n\nLet's look at a minimal example of setting up and using Hangfire in an ASP.NET Core application.
\n\nStep 1: Configuration in Program.cs
\n\nusing Hangfire;\nusing Hangfire.SqlServer;\n\nvar builder = WebApplication.CreateBuilder(args);\n\n// Adding Hangfire with SQL Server storage\nbuilder.Services.AddHangfire(configuration => configuration\n .SetDataCompatibilityLevel(CompatibilityLevel.Version_180)\n .UseSimpleAssemblyNameTypeSerializer()\n .UseRecommendedSerializerSettings()\n .UseSqlServerStorage(builder.Configuration.GetConnectionString("HangfireConnection")));\n\n// Adding Hangfire server\nbuilder.Services.AddHangfireServer();\n\nvar app = builder.Build();\n\n// Enabling the Dashboard\napp.UseHangfireDashboard();\n\n// Example of a simple background job\napp.MapGet("/fire-and-forget", () =>\n{\n var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("Hello from Hangfire!"));\n return $"Job {jobId} has been enqueued.";\n});\n\napp.Run();\n\nStep 2: Creating a Job
\nIn the example above, we used the method <