Asp.NetCore — Background Processes with Hangfire

Şenol ZENGİN
Neyasis Technology
Published in
3 min readApr 3, 2020

What we will read?

  • What is Hangfire
  • How to create Background jobs
  • What are the types of Hangfire Job
  • What is the benefit of using Hangfire

What is Hangfire

It is an open source library that allows us to create, execute and manage background jobs. While the project is running on the server, it is an ideal solution for the functions we want to run in the background according to certain rules and at certain times. It has a handy web interface. Seeing your jobs listed you can stop and start at any time.

How to create Background jobs

We can start by creating a “ZenginHangfire” db in the database.

The database is not created automatically, but it creates the required tables itself. We will see the creation of the tables when you run the application. Your application’s database may differ from the Hangfire database.

  1. We can create our web api project. My project name is “ZenginTaskSchedule”. We add the connection string of the database we created to the application.json file.
"ZenginHangfireCon": "Server=localhost; Database=ZenginHangfire; Trusted_Connection=True;"

2. Add hangfire.AspNetCore and Hangfire.SqlServer packages in NugetSrver.

3. Add Hangfire as a services in ConfigureServices and Write the code blocks stating that we will use this service in the Configure method

ConfigureServices
Conigure Method

4. Start project! you can access hangfire this url (localhost:Port/hangfire)

Hangfire dashboard

What are the types of Hangfire Job

We will examine 4 types of Hangfire Job types.

1- FireAndForgetJobs

The work to be done is defined and then “works once “. We can use BackgroundJob.Enqueue();
Sample scenario “sending information mail”.

FireAndForgotJob Example

2- DelayedJobs

Works only once after a certain time. Sample scenario “user registration mail confirmation”. Also we can use BackgroundJob.Schedule().

DelayedJobs Example

3- RecurringJobs

Used for multiple repetitive jobs. Minutes, hourly, daily, weekly, monthly, yearly CRON times can be specified. We usually use this type. We can create many scenarios for this type. We can use RecurringJob.AddOrUpdate().

RecurringJob Example

4- ContinuationJobs

Jobs that are related to each other and which one needs to wait for the completion of one job are also used. We can use BackgroundJob.ContinueWith().

ContinuationJobs Example

What is the benefit of using Hangfire

  • Easy to use, we can run it in all our .NET applications with a few lines
  • Provides manageability and visibility
  • It is reliable because the jobs are kept in the database. As long as the job is not completed, it will not be completed, and the job will run again in case of any problem until the end of the code block.
  • Handy web interface.

Example Code =>https://github.com/zenginsenol/Hangfire

For more information :)

https://www.hangfire.io/

--

--