Download Hangfire Documentation: Release 1.7 and more Exercises Logic in PDF only on Docsity!
Hangfire Documentation
Release 1.
Hangfire OÜ
Aug 26, 2022
ii
CHAPTER 1
Overview
Hangfire allows you to kick off method calls outside of the request processing pipeline in a very easy, but reliable way.
These method invocations are performed in a background thread and called background jobs.
From the 10.000-feet view the library consists of three main components: client, storage and server. Here is a small
diagram that describes the main processes in Hangfire:
CHAPTER 2
Requirements
Hangfire is not tied to the specific .NET application type. You can use it in ASP.NET web applications, non-ASP.NET
web applications, in console applications or Windows services. Here are the requirements:
- .NET Framework 4.
- Persistent storage (listed below)
- Newtonsoft.Json library 5.0.
Hangfire Documentation, Release 1.
4 Chapter 2. Requirements
Hangfire Documentation, Release 1.
6 Chapter 3. Client
CHAPTER 4
Job Storage
Hangfire keeps background jobs and other information that relates to the processing inside a persistent storage. Per-
sistence helps background jobs to survive on application restarts, server reboots, etc. This is the main distinction
between performing background jobs using CLR’s Thread Pool and Hangfire. Different storage backends are sup-
ported:
- SQL Azure, SQL Server 2008 R2 (and later of any edition, including Express)
- Redis
SQL Server storage can be empowered with MSMQ or RabbitMQ to lower the processing latency.
GlobalConfiguration.Configuration.UseSqlServerStorage("db_connection");
CHAPTER 5
Server
Background jobs are processed by Hangfire Server. It is implemented as a set of dedicated (not thread pool’s) back-
ground threads that fetch jobs from a storage and process them. Server is also responsible to keep the storage clean
and remove old data automatically.
All you need is to create an instance of the BackgroundJobServer class and start the processing:
using ( new BackgroundJobServer()) { Console.WriteLine("Hangfire Server started. Press ENTER to exit..."); Console.ReadLine(); }
Hangfire uses reliable fetching algorithm for each storage backend, so you can start the processing inside a web
application without a risk of losing background jobs on application restarts, process termination and so on.
Hangfire Documentation, Release 1.
10 Chapter 5. Server
Hangfire Documentation, Release 1.
BackgroundJob.Enqueue(() => Console.WriteLine("Hello, world!"));
Please note this is not a delegate, it’s an expression tree. Instead of calling the method immediately, Hangfire serializes
the type (System.Console), method name (WriteLine, with all the parameter types to identify it later), and all
the given arguments, and places it to Storage.
6.1.4 Server
Hangfire Server processes background jobs by querying the Storage. Roughly speaking, it’s a set of background
threads that listen to the Storage for new background jobs, and perform them by de-serializing type, method and
arguments.
You can place this background job server in any process you want, including dangerous ones like ASP.NET – even if
you terminate a process, your background jobs will be retried automatically after restart. So in a basic configuration
for a web application, you don’t need to use Windows Services for background processing anymore.
using ( new BackgroundJobServer()) { Console.ReadLine(); }
6.1.5 Installation
Hangfire is distributed as a couple of NuGet packages, starting from the primary one, Hangfire.Core, that contains all
the primary classes as well as abstractions. Other packages like Hangfire.SqlServer provide features or abstraction
implementations. To start using Hangfire, install the primary package and choose one of the available storages.
After the release of Visual Studio 2017, a completely new way of installing NuGet packages appeared. So I give
up listing all the ways of installing a NuGet package, and fallback to the one available almost everywhere using the
dotnet app.
dotnet add package Hangfire.Core dotnet add package Hangfire.SqlServer
6.1.6 Configuration
Configuration is performed using the GlobalConfiguration class. Its Configuration property provides a
lot of extension methods, both from Hangfire.Core, as well as other packages. If you install a new package, don’t
hesitate to check whether there are new extension methods.
GlobalConfiguration.Configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage("Database=Hangfire.Sample; Integrated Security=True;", new ˓→SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true }) (continues on next page)
12 Chapter 6. Table of Contents
Hangfire Documentation, Release 1.
(continued from previous page) .UseBatches() .UsePerformanceCounters();
Method calls can be chained, so there’s no need to use the class name again and again. Global configuration is made
for simplicity, almost every class of Hangfire allows you to specify overrides for storage, filters, etc. In ASP.NET Core
environments global configuration class is hidden inside the AddHangfire method.
6.1.7 Usage
Here are all the Hangfire components in action, as a fully working sample that prints the “Hello, world!” message
from a background thread. You can comment the lines related to server, and run the program several times – all the
background jobs will be processed as soon as you uncomment the lines again.
using System ; using Hangfire ; using Hangfire.SqlServer ;
namespace ConsoleApplication { class Program { static void Main() { GlobalConfiguration.Configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseColouredConsoleLogProvider() .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage("Database=Hangfire.Sample; Integrated ˓→Security=True;", new SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true });
BackgroundJob.Enqueue(() => Console.WriteLine("Hello, world!"));
using ( var server = new BackgroundJobServer()) { Console.ReadLine(); } } } }
ASP.NET Applications
You can place the background processing in an ASP.NET application without using additional processes like Windows
Services. Hangfire’s code is ready for unexpected process terminations, application pool recycles and restarts during
the deployment process. Since persistent storages are used, you’ll not lose any background job.
6.1. Getting Started 13
Hangfire Documentation, Release 1.
// Startup.cs using Hangfire ; using Hangfire.SqlServer ;
public class Startup { private IEnumerable GetHangfireServers() { GlobalConfiguration.Configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage("Server=.\SQLEXPRESS; Database=HangfireTest; ˓→Integrated Security=True;", new SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true , DisableGlobalLocks = true });
yield return new BackgroundJobServer(); }
public void Configuration(IAppBuilder app) { app.UseHangfireAspNet(GetHangfireServers); app.UseHangfireDashboard();
// Let's also create a sample background job BackgroundJob.Enqueue(() => Debug.WriteLine("Hello world from Hangfire!"));
// ...other configuration logic } }
Using Global.asax.cs file
Configured using the Startup class? Skip this section.
If you can’t use the Startup class for a reason, just use the HangfireAspNet class and modify the Global.
asax.cs file. You’ll not have Hangfire Dashboard in this case, but at least you can start the background processing.
If you’d like to install the dashboard also, please google how to add the Startup class to your project, and go to the
previous section.
// Global.asax.cs using Hangfire ; using Hangfire.SqlServer ;
public class MvcApplication : System.Web.HttpApplication { private IEnumerable GetHangfireServers() { GlobalConfiguration.Configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) (continues on next page)
6.1. Getting Started 15
Hangfire Documentation, Release 1.
(continued from previous page) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage("Server=.\SQLEXPRESS; Database=HangfireTest; ˓→Integrated Security=True;", new SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromMinutes(5), SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5), QueuePollInterval = TimeSpan.Zero, UseRecommendedIsolationLevel = true , DisableGlobalLocks = true });
yield return new BackgroundJobServer(); }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes);
HangfireAspNet.Use(GetHangfireServers);
// Let's also create a sample background job BackgroundJob.Enqueue(() => Debug.WriteLine("Hello world from Hangfire!")); } }
You might also need to disable OWIN’s Startup class detection, when using initialization based on Global.asax.
cs file. The problem is Hangfire.AspNet package depends on Microsoft.Owin.SystemWeb package, and
it requires OWIN Startup class to be present in your web application. If the following exception appears, just disable
the automatic startup in your web.config file as should below.
EntryPointNotFoundException: The following errors occurred while attempting to load ˓→the app.
- No assembly found containing an OwinStartupAttribute.
- No assembly found containing a Startup or [AssemblyName].Startup class.
**
**
Running Application
Run your application in the Debug mode by pressing F5 (this is required to see the output of the Debug.WriteLine
method). Then check the Output window for the following message to see whether background processing has started
successfully.
16 Chapter 6. Table of Contents