What is Hangfire?

Hangfire is an open-source library for .NET that provides a simple way to perform background processing in your application. It allows you to run jobs (methods or functions) asynchronously and schedule them to run at a specific time or regularly.

Main components of Hangfire architecture

By default, it uses SQL Server, but any other supported option is also easy to configure.

Hangfire workflow

Hangfire Workflow

Setting Up Hangfire


NuGet Package

You need to install the Hangfire package.

Hangfire Workflow

Hangfire.SqlServer and Hangfire.The core is installed by default.

Setup Storage

Once you have set up our local database, you must update the appsettings.json file.

Startup.cs setup

Persistence:

Hangfire Workflow

Hangfire Dashboard

Hangfire Workflow

Background jobs

There are several types of background jobs that you can perform using Hangfire:

Fire-and-forget

These are jobs that are executed once and then forgotten. They are used for tasks that need to be performed in the background, but the result doesn't need to be returned to the application immediately.

Delayed jobs

These are jobs that are scheduled to run at a specific time in the future. You can use them to schedule tasks that need to be performed at a specific time, such as sending a reminder email to a user.

Recurring jobs

These are jobs that are scheduled to run repeatedly at a specified interval. You can use them to automate tasks that need to be performed on a regular basis, such as generating reports or performing database cleanup.

Continuations

These are jobs that are executed after a previous job has been completed. You can use them to create a sequence of jobs that need to be performed in a specific order.

Batch jobs

These are jobs that are grouped together and executed as a single unit. You can use them to perform a set of related tasks that need to be executed together.

Executing jobs


1. Fire and Forget jobs

2. Delayed jobs

3. Continuation jobs

4. Reccuring jobs

Let's create another endpoint:

        [HttpGet("RecurringJob")]
        public IActionResult recurringJob()
        {
            RecurringJob.AddOrUpdate("myrecurringjob", () => Console.WriteLine("hello testing hangfire RecurringJob"), Cron.Minutely());
            //sendmail();
            return Ok("recurring job is done");
        }

5. Batch jobs