DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Empowering Real-World Solutions the Synergy of AI and .NET
  • New ORM Framework for Kotlin
  • The Generic Way To Convert Between Java and PostgreSQL Enums
  • Let’s Build an End-to-End NFT Project Using Truffle Suite

Trending

  • Designing AI Multi-Agent Systems in Java
  • Prioritizing Cloud Security Risks: A Developer's Guide to Tackling Security Debt
  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • Infrastructure as Code (IaC) Beyond the Basics
  1. DZone
  2. Data Engineering
  3. Databases
  4. Hangfire Introduction and Implementation in .NET Core 6 Web API

Hangfire Introduction and Implementation in .NET Core 6 Web API

A step-by-step tutorial introduction to Hangfire and its implementation using .NET Core 6 with background information, code blocks, and guide pictures.

By 
Jaydeep Patil user avatar
Jaydeep Patil
·
Nov. 23, 22 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
8.4K Views

Join the DZone community and get the full member experience.

Join For Free

Prerequisites

  • Basic understanding of .NET Core 6 API and C#.
  • Visual Studio 2022
  • SQL Server

Agenda

  • Create .NET Core API using version 6
  • Configure Hangfire in .NET
  • Look into the different types of jobs that are present in Hangfire.

Overview

  • Hangfire is open-source and used to schedule the job at a particular event and time.
  • It is also used to create, process, and manage your background jobs.
  • We use this in background processing without user intervention.
  • Hangfire is reliable and persistent. It will take care of all things once the job is scheduled.
  • Hangfire dashboard is also available for us to manage all things easily.

Why Hangfire is Required in Background Processing

  • Sometimes we need to do lengthy operations like database updates and database maintenance so it’s managed periodically. 
  • Batch import from XML, JSON, and YAML files.
  • Recurring reports on a periodic basis.
  • Mass notification on subscription and sign up basis.

So, these are things that we are able to do periodically over a certain period of time as per our requirements.

There are different types of jobs that are present in Hangfire. We will look at them one by one.

Fire-and-Forget Job

Fire and Forget jobs are executed only one time after certain conditions which we provide.

Delayed Job

A delayed job is also executed only once but after a specific interval of time.

Recurring Job

Recurring job is executed many times after the specified condition and time interval.

Continuations Job

The continuation job is executed when its parent job is executed and finished.

There are also two jobs present now in Hangfire: one is Batch Job and the other is Batch Continuation, which are present in the Hangfire Pro version and are used to execute multiple jobs in batch as a single entity.

Step 1

Open Visual Studio 2022 and create a new .NET Core Web API Project.

Create a New Project

Step 2

Provide the project name “HangfireDemo” and then provide the location.

Configure New Project

Step 3

Provide additional information like .NET Framework 6, Configure HTTPS, and enable Open API support and swagger.

Additional Information

Step 4

Install the Hangfire NuGet package.

Hangfire NuGet Package

Step 5

Create API Controller and name it as “ProductController.”

C#
 
using Hangfire;
using Microsoft.AspNetCore.Mvc;
namespace HangfireDemo.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        [HttpGet]
        [Route("login")]
        public String Login()
        {
            //Fire - and - Forget Job - this job is executed only once
            var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("Welcome to Shopping World!"));
            return $"Job ID: {jobId}. Welcome mail sent to the user!";
        }
        [HttpGet]
        [Route("productcheckout")]
        public String CheckoutProduct()
        {
            //Delayed Job - this job executed only once but not immedietly after some time.
            var jobId = BackgroundJob.Schedule(() => Console.WriteLine("You checkout new product into your checklist!"),TimeSpan.FromSeconds(20));
            return $"Job ID: {jobId}. You added one product into your checklist successfully!";
        }
        [HttpGet]
        [Route("productpayment")]
        public String ProductPayment()
        {
            //Fire and Forget Job - this job is executed only once
            var parentjobId = BackgroundJob.Enqueue(() => Console.WriteLine("You have done your payment suceessfully!"));
            //Continuations Job - this job executed when its parent job is executed.
            BackgroundJob.ContinueJobWith(parentjobId, () => Console.WriteLine("Product receipt sent!"));
            return "You have done payment and receipt sent on your mail id!";
        }
        [HttpGet]
        [Route("dailyoffers")]
        public String DailyOffers()
        {
            //Recurring Job - this job is executed many times on the specified cron schedule
            RecurringJob.AddOrUpdate(() => Console.WriteLine("Sent similar product offer and suuggestions"), Cron.Daily);
            return "offer sent!";
        }
    }
}


  • Here we created different endpoints based on product scenarios like when a user logs into to the shopping site, it will get a welcome message on an immediate basis using the fire-and-forget job.
  • After that, we created another endpoint related to the product checklist. When the user adds a new product to the checklist, it will get notified and reminded after a few seconds that you are adding a new product to your checklist.
  • In the third endpoint, we created a job for payment. When the user completes the process, it will get an email immediately using the fire-and-forget job and, later on, when this job is executed, the continuation job will get executed, which is the child job and executed after the parent job will get executed.
  • Finally, in the last endpoint, we want to send special offers on a monthly basis. For that, we use a recurring job that will execute continuously in the background after specified Cron conditions.

Step 6

Finally, let’s configure things in Program.cs classes related to Hangfire, like SQL Server Database and middleware, which we need.

C#
 
using Hangfire;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.

//Hangfire
builder.Services.AddHangfire(x => x.UseSqlServerStorage(@"Data Source=DESKTOP-8RL8JOG;Initial Catalog=hangfire;Integrated Security=True;Pooling=False"));
builder.Services.AddHangfireServer();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseHangfireDashboard();
app.UseAuthorization();
app.MapControllers();
app.Run();


So here we register a few things related to Hangfire and the SQL Server database.

Step 7

Now, after you run the application, this Swagger window will open, and using this, we will perform operations one by one after hitting API endpoints.

Hangfire Demo

Also, it will create the following tables in the database related to Hangfire to manage jobs.

Manage Jobs

Step 8

You can now also open the Hangfire dashboard to manage background running jobs after hitting the same API port in another window https://localhost:7204/hangfire.

Overview

Now we are going to execute API endpoints one by one and check the newly created jobs in the Hangfire dashboard.

First, when we hit the login endpoint from Swagger UI, it will create one job and execute that job immediately as shown in the below images:

Queues

Succeeded Jobs

Console.Writeline

Here, in Hangfire Dashboard, you can see all the details about jobs like succeeded, scheduled, failed, and processing, as I have shown in the above images.

Now we hit another endpoint product checkout and it will schedule one background job and execute once after a specified time interval.

Scheduled Jobs

After this, we are going to hit the third endpoint, which is to create a continuation job and execute it after its parent job gets executed, as shown in the image here. First, the parent job is executed, and then the immediate child job, which is the continuation job, is executed. 

Succeeded Jobs 2

Finally, we are going to hit our last API endpoint and check how the recurring job is executed one by one.

Recurring Jobs

Conclusion

Here you can see how recurring jobs are created and executed one by one after a specific time interval.

So, this is all about Hangfire, which we used in .NET Core to schedule background jobs as per our requirements.

I hope you understand a few things related to Hangfire.

Happy Coding!

API Database HTTPS Web API career Dashboard (Mac OS) Net (command) Schedule (computer science) SENT (protocol) Data Types

Published at DZone with permission of Jaydeep Patil. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Empowering Real-World Solutions the Synergy of AI and .NET
  • New ORM Framework for Kotlin
  • The Generic Way To Convert Between Java and PostgreSQL Enums
  • Let’s Build an End-to-End NFT Project Using Truffle Suite

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!