facebook

Blog

Stay updated

Let’s discover together how to perform activities in background with a professional tool
How to schedule activities with Hangfire
Tuesday, April 09, 2019

user story has been recently assigned to me. It is required to integrate Hangfire, and then decide how to create the jobs.

Hangfire is a library available for .NET and .NET Core, that permits to schedule jobs in background with no need of Windows Service or other external processes help. Since I was in ignorance of it, I trust completely in its documentation, which seems to be really good. Hangfire’s main components are:

  • Client – Responsible for jobs creation;
  • Job Storage – Provides a persistence service for jobs and related information;
  • Server – Recovers data from the storage and processes them.

Let’s step back to the user story’s tasks. To describe my experience, I create a simple application, starting from a template in Visual Studio: specifically, I decided to create an ASP.NET Core Web Application with a Front-end made in Angular. The application has a simple Homepage with a button. When you click on the button, a counter starts running. We will transform this action into a job that will be scheduled in Hangfire.

Let’s assimilate Hangfire in our project by the addiction of the related Nuget package.

In the Startup.cs, we register Hangfire as service and then we add Hangfire Server to the configuration.

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    //...some code
 
    // Add Hangfire services
    services.AddHangfire(s => s.UseSqlServerStorage(Configuration.GetConnectionString("HangfireDemo")));
 
    //...some code
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //...some code
 
    //Hangfire
    app.UseHangfireServer();
    app.UseHangfireDashboard("/hangfire");
 
    //...some code
 
});

We can note that, as we register Hangfire, the storage for our jobs will be defined. In order to make it simpler, I decided to use the SQLServer local instance, where a new database has been created (HangfireDemoDB) ), but it’s possible to use other storage types too, as Database NoSQL, or MongoDB or in-memory solutions as Redis.

Within the file appsettings.json a connection string to DB has been defined.

"ConnectionStrings": {
    "HangfireDemo": "Server=(LocalDb)\\MSSQLLocalDB;Database=HangfireDemoDB; Trusted_Connection=True;MultipleActiveResultSets=true"
}

As the application starts, many different tables will be created and they will contain the jobs and related information, as I already wrote.

The click on the button “increment counter” causes a HTTP PUT request, with whom we pass to the Backend, the present value of our counter. Right inside the Controller , that manages this request, we must schedule our jobs, whose action would be to increment the counter’s value.

[HttpPut]
[Route("[action]")]
public void SendCurrentCounter([FromBody] Counter currentCounter)
{
    counter.Value = currentCounter.Value;
    BackgroundJob.Enqueue(() => incrementCounter());
}
 
public void incrementCounter()
{
    counter.Value++;
}

The job we are going to schedule is of fire-and-forget type, the better type for our example, among all types available. With Hangfire, we can schedule jobs with different scheduling types too: as example, delayed jobs, that are those jobs scheduled after a period of time, or the recurring jobs, that have to be performed at regular intervals.

In the configuration of our example, we also insert the Hangfire Dashboard, that is reachable, in this case, to the address:

[host]:[port]/hangfire

This graphical interface allows us to have a graphic representation of scheduled jobs and provide us many useful information about them, as the jobs, that have been rightly scheduled and those failed. Below we can see the result of the scheduling of ten jobs, both on the dashboard and on DB.

and on the DB.

We have just scratched the surface of this topic, Hangfire makes available many other functionalities and is one of the tools can’t miss in your “IT arsenal”.

You can find the code on my github to this address:

See you next