Background Processing In ASP.NET Core With Hangfire

In this article, we will learn an easy way to perform background processing in .NET Core applications. A background process/job is a process that runs behind the scenes without user intervention. Hangfire is a simple, persistent, transparent, reliable, and efficient open-source library used to perform background processing in .NET and .NET Core applications.
 

Why Background Processing?

  • Lengthy operations like database updates
  • Invoice generation
  • Monthly reports
  • Automatic subscription renewal
  • Email upon sign-up

Background Jobs/Tasks

  •   Fire and Forget 
  •   Delayed
  •   Periodic and Scheduled
  •   Continuations
Fire and Forget
 
These tasks happen only once. For example, sending a welcome email when a user signup.

Delayed
 
Delayed tasks are like fire and forget but do not execute them as soon as the action is taken instead, we define a time when the background job is going to run. For example when we want to send a voucher or discount to a user 5 hours after they signed up.
 
Periodic and Scheduled
 
These jobs are performed periodically based on a schedule, for example, generating marketing emails or generating invoices.
 
Continuations
 
Continuations are executed when their parent job has been finished.
 
Step 1
 
Create a new project as shown below,

 
 
 
Step 2
 
Let's install the Hangfire Nuget package as shown below,
 
 
Step 3
 
Open Startup.cs file and change as per the readme file from hangfire. Inside the configure services plese add the hangfire services as shown below,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Hangfire;  
  6. using Microsoft.AspNetCore.Builder;  
  7. using Microsoft.AspNetCore.Hosting;  
  8. using Microsoft.AspNetCore.HttpsPolicy;  
  9. using Microsoft.AspNetCore.Mvc;  
  10. using Microsoft.Extensions.Configuration;  
  11. using Microsoft.Extensions.DependencyInjection;  
  12. using Microsoft.Extensions.Hosting;  
  13. using Microsoft.Extensions.Logging;  
  14.   
  15. namespace hangfire_webapi  
  16. {  
  17.     public class Startup  
  18.     {  
  19.         public Startup(IConfiguration configuration)  
  20.         {  
  21.             Configuration = configuration;  
  22.         }  
  23.   
  24.         public IConfiguration Configuration { get; }  
  25.   
  26.         // This method gets called by the runtime. Use this method to add services to the container.  
  27.         public void ConfigureServices(IServiceCollection services)  
  28.         {  
  29.             services.AddHangfire(x => x.UseSqlServerStorage(@"Data Source=.;Initial Catalog=hangfire-webapi-db;Integrated Security=True;Pooling=False"));  
  30.             services.AddHangfireServer();  
  31.             services.AddControllers();  
  32.         }  
  33.   
  34.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  35.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  36.         {  
  37.             if (env.IsDevelopment())  
  38.             {  
  39.                 app.UseDeveloperExceptionPage();  
  40.             }  
  41.   
  42.             app.UseHttpsRedirection();  
  43.             app.UseHangfireDashboard();  
  44.             app.UseRouting();  
  45.   
  46.             app.UseAuthorization();  
  47.   
  48.             app.UseEndpoints(endpoints =>  
  49.             {  
  50.                 endpoints.MapControllers();  
  51.             });  
  52.         }  
  53.     }  
  54. }  
Step 4
 
Let's configure the database open SQL server and create a database as shown below,

 
Step 5
 
Create a controller and schedule all types of background jobs,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Hangfire;  
  6. using Microsoft.AspNetCore.Mvc;  
  7. using Microsoft.Extensions.Logging;  
  8.   
  9. namespace hangfire_webapi.Controllers  
  10. {  
  11.     [ApiController]  
  12.     [Route("api/[controller]")]  
  13.     public class HangfireController : ControllerBase  
  14.     {  
  15.         [HttpPost]  
  16.         [Route("[action]")]  
  17.         public IActionResult Welcome()  
  18.         {  
  19.             var jobId = BackgroundJob.Enqueue(() => SendWelcomeEmail("Welcome to our app"));  
  20.   
  21.             return Ok($"Job ID: {jobId}. Welcome email sent to the user!");  
  22.         }  
  23.   
  24.         [HttpPost]  
  25.         [Route("[action]")]  
  26.         public IActionResult Discount()  
  27.         {  
  28.             int timeInSeconds = 30;  
  29.             var jobId = BackgroundJob.Schedule(() => SendWelcomeEmail("Welcome to our app"), TimeSpan.FromSeconds(timeInSeconds));  
  30.   
  31.             return Ok($"Job ID: {jobId}. Discount email will be sent in {timeInSeconds} seconds!");  
  32.         }  
  33.   
  34.         [HttpPost]  
  35.         [Route("[action]")]  
  36.         public IActionResult DatabaseUpdate()  
  37.         {  
  38.             RecurringJob.AddOrUpdate(() => Console.WriteLine("Database updated"), Cron.Minutely);  
  39.             return Ok("Database check job initiated!");  
  40.         }  
  41.   
  42.         [HttpPost]  
  43.         [Route("[action]")]  
  44.         public IActionResult Confirm()  
  45.         {  
  46.             int timeInSeconds = 30;  
  47.             var parentJobId = BackgroundJob.Schedule(() => Console.WriteLine("You asked to be unsubscribed!"), TimeSpan.FromSeconds(timeInSeconds));  
  48.   
  49.             BackgroundJob.ContinueJobWith(parentJobId, () => Console.WriteLine("You were unsubscribed!"));  
  50.   
  51.             return Ok("Confirmation job created!");  
  52.         }  
  53.   
  54.   
  55.         public void SendWelcomeEmail(string text)  
  56.         {  
  57.             Console.WriteLine(text);  
  58.         }  
  59.     }  
  60. }  
Let's test through Postman,


Now we can see the hangfire Dashboard as below,

Conclusion


In this article, we discussed how to schedule background jobs/tasks using .Net core, Hangfire, and SQL server. I hope you all enjoyed reading this and learned from it. For better understanding download the source code.