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. namespace hangfire_webapi
  15. {
  16. public class Startup
  17. {
  18. public Startup(IConfiguration configuration)
  19. {
  20. Configuration = configuration;
  21. }
  22. public IConfiguration Configuration { get; }
  23. // This method gets called by the runtime. Use this method to add services to the container.
  24. public void ConfigureServices(IServiceCollection services)
  25. {
  26. services.AddHangfire(x => x.UseSqlServerStorage(@"Data Source=.;Initial Catalog=hangfire-webapi-db;Integrated Security=True;Pooling=False"));
  27. services.AddHangfireServer();
  28. services.AddControllers();
  29. }
  30. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  31. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  32. {
  33. if (env.IsDevelopment())
  34. {
  35. app.UseDeveloperExceptionPage();
  36. }
  37. app.UseHttpsRedirection();
  38. app.UseHangfireDashboard();
  39. app.UseRouting();
  40. app.UseAuthorization();
  41. app.UseEndpoints(endpoints =>
  42. {
  43. endpoints.MapControllers();
  44. });
  45. }
  46. }
  47. }
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. namespace hangfire_webapi.Controllers
  9. {
  10. [ApiController]
  11. [Route("api/[controller]")]
  12. public class HangfireController : ControllerBase
  13. {
  14. [HttpPost]
  15. [Route("[action]")]
  16. public IActionResult Welcome()
  17. {
  18. var jobId = BackgroundJob.Enqueue(() => SendWelcomeEmail("Welcome to our app"));
  19. return Ok($"Job ID: {jobId}. Welcome email sent to the user!");
  20. }
  21. [HttpPost]
  22. [Route("[action]")]
  23. public IActionResult Discount()
  24. {
  25. int timeInSeconds = 30;
  26. var jobId = BackgroundJob.Schedule(() => SendWelcomeEmail("Welcome to our app"), TimeSpan.FromSeconds(timeInSeconds));
  27. return Ok($"Job ID: {jobId}. Discount email will be sent in {timeInSeconds} seconds!");
  28. }
  29. [HttpPost]
  30. [Route("[action]")]
  31. public IActionResult DatabaseUpdate()
  32. {
  33. RecurringJob.AddOrUpdate(() => Console.WriteLine("Database updated"), Cron.Minutely);
  34. return Ok("Database check job initiated!");
  35. }
  36. [HttpPost]
  37. [Route("[action]")]
  38. public IActionResult Confirm()
  39. {
  40. int timeInSeconds = 30;
  41. var parentJobId = BackgroundJob.Schedule(() => Console.WriteLine("You asked to be unsubscribed!"), TimeSpan.FromSeconds(timeInSeconds));
  42. BackgroundJob.ContinueJobWith(parentJobId, () => Console.WriteLine("You were unsubscribed!"));
  43. return Ok("Confirmation job created!");
  44. }
  45. public void SendWelcomeEmail(string text)
  46. {
  47. Console.WriteLine(text);
  48. }
  49. }
  50. }
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.