Hangfire Usage

This sample illustrates the use of Hangfire to send messages from within an NServiceBus endpoint.

Hangfire - An easy way to perform background processing in .NET and .NET Core applications. Hangfire is an open-source framework that helps you to create, process and manage your background jobs.

The approach used in this sample can mitigate some of the architectural drawbacks of the NServiceBus Scheduler. The NServiceBus scheduler is built on top of the Timeout Manager which leverages the queuing system to trigger scheduled actions. Under heavy load there may be some disparity between the expected time of a scheduled action and execution time due to the delay between timeout messages being generated and processed.

Running the project

Start both the Scheduler and Receiver projects.

At startup Scheduler will schedule sending a message to Receiver every minute.

Receiver will handle the message.

Code Walk-through

Endpoint Helper

This is a helper class used to make the NServiceBus IEndpointInstance available inside Hangfire jobs. In this sample it is implemented as a static property.

The Hangfire scheduler implements the IDisposable interface. For cleanup purposes, keep a reference to the scheduler instance and call Dispose() at shutdown. Alternatively, use dependency injection and let cleanup be automatically be managed.

Scale Out

Note that in this sample an instance of the Hangfire scheduler is configured to run in every endpoint's instance. If an endpoint is scaled out then the configured jobs will be executed by each of the running instances. A persistent job storage can help to manage the Hangfire scheduler shared state, including jobs, triggers, calendars, etc.