Docsity

Hangfire Documentation: Installing and Configuring Background Jobs in ASP.NET, Summaries of Logic

Partial preview of the text

Download Hangfire Documentation: Installing and Configuring Background Jobs in ASP.NET and more Summaries Logic in PDF only on Docsity!

HangFire Documentation

Release 1.

Sergey Odinokov

August 27, 2015

ii

Incredibly easy way to perform fire-and-forget, delayed and recurring jobs inside ASP.NET applications. No

Windows Service / Task Scheduler required. Backed by Redis, SQL Server, SQL Azure or MSMQ.

Hangfire provides unified programming model to handle background tasks in a reliable way and run them on shared

hosting, dedicated hosting or in cloud. You can start with a simple setup and grow computational power for background

jobs with time for these scenarios:

  • mass notifications/newsletter;
  • batch import from xml, csv, json;
  • creation of archives;
  • firing off web hooks;
  • deleting users;
  • building different graphs;
  • image/video processing;
  • purge temporary files;
  • recurring automated reports;
  • database maintenance; -... and so on.

Hangfire is a .NET Framework alternative to Sidekiq, Resque, delayed_job.

Contents 1

CHAPTER 1

Contents

1.1 Project pages

Site http://hangfire.io

Documentation http://docs.hangfire.io

Forum http://discuss.hangfire.io

NuGet Packages https://www.nuget.org/packages?q=hangfire

Development https://github.com/HangfireIO/Hangfire

Issues https://github.com/HangfireIO/Hangfire/issues

Release Notes https://github.com/HangfireIO/Hangfire/releases

1.2 Quick start

1.2.1 Installation

There are a couple of packages for Hangfire available on NuGet. To install Hangfire into your ASP.NET application

with SQL Server storage, type the following command into the Package Manager Console window:

PM> Install-Package Hangfire

1.2.2 Configuration

After installing the package, add or update the OWIN Startup class with the following lines:

public void Configure(IAppBuilder app) { app.UseHangfire(config => { config.UseSqlServerStorage(""); config.UseServer(); }); }

Then open the Hangfire Dashboard to test your configuration. Please, build the project and open the following URL

in a browser:

1.2.3 Usage

Add a job...

Hangfire handles different types of background jobs, and all of them are invoked on a separate execution context.

Fire-and-forget

This is the main background job type, persistent message queues are used to handle it. Once you create a fire-and-

forget job, it is being saved to its queue ("default" by default, but multiple queues supported). The queue is

listened by a couple of dedicated workers that fetch a job and perform it.

BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget"));

Delayed method invocation

If you want to delay the method invocation for a certain type, call the following method. After the given delay the job

will be put to its queue and invoked as a regular fire-and-forget job.

BackgroundJob.Schedule(() => Console.WriteLine("Delayed"), TimeSpan.FromDays(1));

Recurring tasks

To call a method on a recurrent basis (hourly, daily, etc), use the RecurringJob class. You are able to specify the

schedule using CRON expressions to handle more complex scenarios.

RecurringJob.AddOrUpdate(() => Console.Write("Recurring"), Cron.Daily);

... and relax

Hangfire saves your jobs into persistent storage and processes them in a reliable way. It means that you can abort

Hangfire worker threads, unload application domain or even terminate the process, and your jobs will be processed

anyway 1. Hangfire flags your job as completed only when the last line of your code was performed, and knows that

the job can fail before this last line. It contains different auto-retrying facilities, that can handle either storage errors

or errors inside your code.

This is very important for generic hosting environment, such as IIS Server. They can contain different optimizations,

timeouts and error-handling code (that may cause process termination) to prevent bad things to happen. If you are not

using the reliable processing and auto-retrying, your job can be lost. And your end user may wait for its email, report,

notification, etc. indefinitely.

1.3 Features

1.3.1 Queue-based processing

Instead of invoking a method synchronously, place it on a persistent queue, and Hangfire worker thread will take it

and perform within its own execution context:

(^1) But when your storage becomes broken, Hangfire can not do anything. Please, use different failover strategies for your storage to guarantee the processing of each job in case of a disaster.

4 Chapter 1. Contents

1.3.7 Guaranteed processing

Hangfire was made with the knowledge that the hosting environment can kill all the threads on each line. So, it does

not remove the job until it was successfully completed and contains different implicit retry logic to do the job when its

processing was aborted.

1.3.8 Instance method calls

All the examples above uses static method invocation, but instance methods are supported as well:

public class EmailService { public void Send() { } }

BackgroundJob.Enqueue(x => x.Send());

When a worker sees that the given method is an instance-method, it will activate its class first. By default, the

Activator.CreateInstace method is being used, so only classes with default constructors are supported by

default. But you can plug in your IoC container and pass the dependencies through the constructor.

1.3.9 Culture capturing

When you marshal your method invocation into another execution context, you should be able to preserve some

environment settings. Some of them – Thread.CurrentCulture and Thread.CurrentUICulture are au-

tomatically being captured for you.

It is done by the PreserveCultureAttribute class that is applied to all of your methods by default.

1.4 Advanced Features

1.4.1 Cancellation tokens

Hangfire can tell your methods were aborted or canceled due to shutdown event, so you can stop them gracefully using

job cancellation tokens that are similar to the regular CancellationToken class.

public void Method(IJobCancellationToken token) { for ( var i = 0; i < Int32.MaxValue; i++) { token.ThrowIfCancellationRequested(); Thread.Sleep(1000); } }

1.4.2 IoC Containers

In case you want to improve the testability of your job classes or simply don’t want to use a huge amount of dif-

ferent factories, you should use instance methods instead of static ones. But you either need to somehow pass the

dependencies into these methods and the default job activator does not support parameterful constructors.

6 Chapter 1. Contents

Don’t worry, you can use your favourite IoC container that will instantiate your classes. There are two packages,

Hangfire.Ninject and Hangfire.Autofac for their respective containers. If you are using another container,

please, write it yourself (on a basis of the given packages) and contribute to Hangfire project.

1.4.3 Logging

Hangfire uses the Common.Logging library to log all its events. It is a generic library and you can plug it to your

logging framework using adapters. Please, see the list of available adapters on NuGet Gallery.

1.4.4 Web Garden and Web Farm friendly

You can run multiple Hangfire instances, either on the same or different machines. It uses distributed locking to prevent

race conditions. Each Hangfire instance is redundant, and you can add or remove instances seamlessly (but control the

queues they listen).

1.4.5 Multiple queues processing

Hangfire can process multiple queues. If you want to prioritize your jobs or split the processing across your servers

(some processes the archive queue, others – the images queue, etc), you can tell Hangfire about your decisions.

To place a job into a different queue, use the QueueAttribute class on your method:

[Queue("critical")] public void SomeMethod() { }

BackgroundJob.Enqueue(() => SomeMethod());

To start to process multiple queues, you need to update your OWIN bootstrapper’s configuration action:

app.UseHangfire(config => { config.UseServer("critical", "default"); });

The order is important, workers will fetch jobs from the critical queue first, and then from the default queue.

1.4.6 Concurrency level control

Hangfire uses its own fixed worker thread pool to consume queued jobs. Default worker count is set to

Environment.ProcessorCount * 5. This number is optimized both for CPU-intensive and I/O intensive

tasks. If you experience excessive waits or context switches, you can configure amount of workers manually:

app.UseHangfire(config => { config.UseServer(100); });

// or var server = new BackgroundJobServer(100);

1.4. Advanced Features 7

_db.Comments.Add(model); _db.SaveChanges(); }

return RedirectToAction("Index"); }

Installing Postal

First, install the Postal NuGet package:

Install-Package Postal

Then, create ~/Models/NewCommentEmail.cs file with the following contents:

using Postal ;

namespace Hangfire.Mailer.Models { public class NewCommentEmail : Email { public string To { get ; set ; } public string UserName { get ; set ; } public string Comment { get ; set ; } } }

Create a corresponding template for this email by adding the ~/Views/Emails/NewComment.cshtml file:

@model Hangfire.Mailer.Models.NewCommentEmail To: @Model.To From: [email protected] Subject: New comment posted

Hello, There is a new comment from @Model.UserName:

@Model.Comment

<

And call Postal to sent email notification from the Create controller action:

[HttpPost] public ActionResult Create(Comment model) { if (ModelState.IsValid) { _db.Comments.Add(model); _db.SaveChanges();

var email = new NewCommentEmail { To = "[email protected]", UserName = model.UserName, Comment = model.Text };

1.5. Tutorials 9

email.Send(); }

return RedirectToAction("Index"); }

Then configure the delivery method in the web.config file (by default, tutorial source code uses C:\Temp directory

to store outgoing mail):

<system.net> <smtp deliveryMethod="SpecifiedPickupDirectory" > <specifiedPickupDirectory pickupDirectoryLocation="C:\Temp" /> </system.net>

That’s all. Try to create some comments and you’ll see notifications in the pickup directory.

Further considerations

But why should a user wait until the notification was sent? There should be some way to send emails asynchronously,

in the background, and return a response to the user as soon as possible.

Unfortunately, asynchronous controller actions does not help in this scenario, because they do not yield response to

the user while waiting for the asynchronous operation to complete. They only solve internal issues related to thread

pooling and application capacity.

There are great problems with background threads also. You should use Thread Pool threads or custom ones that

are running inside ASP.NET application with care – you can simply lose your emails during the application recycle

process (even if you register an implementation of the IRegisteredObject interface in ASP.NET).

And you are unlikely to want to install external Windows Services or use Windows Scheduler with a console applica-

tion to solve this simple problem (we are building a personal blog, not an e-commerce solution).

Installing Hangfire

To be able to put tasks into the background and not lose them during application restarts, we’ll use Hangfire. It can

handle background jobs in a reliable way inside ASP.NET application without external Windows Services or Windows

Scheduler.

Install-Package Hangfire

Hangfire uses SQL Server or Redis to store information about background jobs. So, let’s configure it. Add or update

the OWIN Startup class as written here.

public void Configure(IAppBuilder app) { app.UseHangfire(config => { app.UseSqlServerStorage("MailerDb"); app.UseServer(); }); }

The SqlServerStorage class will install all database tables automatically on application start-up (but you are able

to do it manually).

10 Chapter 1. Contents

That’s all! Try to create some comments and see the C:\Temp path. You also can check your background jobs at

http://<your-app>/hangfire. If you have any questions, you are welcome to use the comments form below.

Note: If you experience assembly load exceptions, please, please delete the following sections from the

web.config file (I forgot to do this, but don’t want to re-create the repository):

<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" /> <assemblyIdentity name="Common.Logging" publicKeyToken="af08829b84f0328e" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-2.2.0.0" newVersion="2.2.0.0" />

Automatic retries

When the emailService.Send method throws an exception, HangFire will retry it automatically after a delay

(that is increased with each attempt). The retry attempt count is limited (10 by default), but you can increase it. Just

apply the AutomaticRetryAttribute to the NotifyNewComment method:

[AutomaticRetry(20)] public static void NotifyNewComment( int commentId) { /* ... */ }

Logging

You can log cases when the maximum number of retry attempts has been exceeded. Try to create the following class:

public class LogFailureAttribute : JobFilterAttribute, IApplyStateFilter { private static readonly ILog Logger = LogManager.GetCurrentClassLogger();

public void OnStateApplied(ApplyStateContext context, IWriteOnlyTransaction transaction) { var failedState = context.NewState as FailedState; if (failedState != null ) { Logger.Error( String.Format("Background job #{0} was failed with an exception.", context.JobId), failedState.Exception); } }

public void OnStateUnapplied(ApplyStateContext context, IWriteOnlyTransaction transaction) { } }

And add it:

Either globally by calling the following method at application start:

12 Chapter 1. Contents

GlobalJobFilters.Filters.Add( new LogFailureAttribute());

Or locally by applying the attribute to a method:

[LogFailure] public static void NotifyNewComment( int commentId) { /* ... */ }

Fix-deploy-retry

If you made a mistake in your NotifyNewComment method, you can fix it and restart the failed background job via

the web interface. Try it:

// Break background job by setting null to emailService: var emailService = null ;

Compile a project, add a comment and go to the web interface by typing http://<your-app>/hangfire.

Exceed all automatic attempts, then fix the job, restart the application, and click the Retry button on the Failed jobs

page.

Preserving current culture

If you set a custom culture for your requests, Hangfire will store and set it during the performance of the background

job. Try the following:

// HomeController/Create action Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("es-ES"); BackgroundJob.Enqueue(() => NotifyNewComment(model.Id));

And check it inside the background job:

public static void NotifyNewComment( int commentId) { var currentCultureName = Thread.CurrentThread.CurrentCulture.Name; if (currentCultureName != "es-ES") { throw new InvalidOperationException(String.Format("Current culture is {0}", currentCultureNam } // ...

1.5.2 Highlighter Tutorial

Simple sample https://github.com/odinserj/Hangfire.Highlighter

Full sample http://highlighter.hangfire.io, sources

1.5. Tutorials 13

Then, we need a controller to handle web requests. So scaffold an MVC 5 Controller - Empty controller and call it

HomeController:

Our controller contains now only Index action and looks like:

public class HomeController : Controller { public ActionResult Index() { return View(); } }

We have a controller with a single action. To test that our application is working, scaffold an empty view for Index

action.

1.5. Tutorials 15

The view scaffolding process also adds additional components to the project, like Bootstrap, jQuery, etc. After these

steps my solution looks like:

16 Chapter 1. Contents