Introduction

In this article we will learn about the Hangfire - .Net Library to make our background tasks and jobs easier in ASP.NET 5.0. As we all know, its newly launched Framework officially released in November. Here I am sharing the link to install the SDK for .Net 5
Prerequisites
  1. What is Hangfire and why do I need background tasks.
  2. Setup and Configure Hangfire
  3. Secure the Hangfire Dashboard.
  4. Hangfire Retention Time.
  5. Persistence with SQL Database.

What is Hangfire and why do we need to use this?

Hangfire is a .Net Library which helps to create background tasks and make jobs easier in .Net applications. It supports all types of tasks like "fire and forget" and "recurring" and continous jobs as well. You can learn more about this here: Hangfire
Why do I need background tasks?
Background tasks are important in cases where you need to perform an operation or to schedule a task for a particular time. With the background task, the process can continue running in the background where the user cannot wait for the step by step process.

Setup and Configure Hangfire

Create and set up project template with .Net 5
In order to configure Hangfire, we need to install hangfire related packages. Below are the 4 packages that help in configuration and setup authentication and to store job-related information in SQL.
In this project, I have used Data insertion to Database using background tasks - Hangfire and the Code first approach.
Models
Employee.cs
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. namespace Hangfire.Model
  7. {
  8. public class Employee
  9. {
  10. [Key]
  11. public int Id { get; set; }
  12. public string EmployeeName { get; set; }
  13. public string Designation { get; set; }
  14. }
  15. }
AppDbContext
EmployeeDbContext.cs
  1. using Hangfire.Model;
  2. using Microsoft.EntityFrameworkCore;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. namespace Hangfire.AppDbContext
  8. {
  9. public partial class EmployeeDbContext : DbContext
  10. {
  11. public EmployeeDbContext(DbContextOptions options) : base(options)
  12. {
  13. }
  14. public DbSet<Employee> Employees { get; set; }
  15. }
  16. }
appsettings.js
  1. "ConnectionStrings": {
  2. "myconn": "server=N-20RJPF2CFK06\\SQLEXPRESS; database=Temp;Trusted_Connection=True;"
  3. },
Configure the connection string and Hangfire and services injection in the startup file.
Startup.cs
  1. using Hangfire.AppDbContext;
  2. using Hangfire.Services;
  3. using HangfireBasicAuthenticationFilter;
  4. using Microsoft.AspNetCore.Builder;
  5. using Microsoft.AspNetCore.Hosting;
  6. using Microsoft.AspNetCore.HttpsPolicy;
  7. using Microsoft.AspNetCore.Mvc;
  8. using Microsoft.EntityFrameworkCore;
  9. using Microsoft.Extensions.Configuration;
  10. using Microsoft.Extensions.DependencyInjection;
  11. using Microsoft.Extensions.Hosting;
  12. using Microsoft.Extensions.Logging;
  13. using Microsoft.OpenApi.Models;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Linq;
  17. using System.Threading.Tasks;
  18. namespace Hangfire
  19. {
  20. public class Startup
  21. {
  22. private static IEmployeeService employeeService;
  23. private readonly Job jobscheduler = new Job(employeeService);
  24. public Startup(IConfiguration configuration)
  25. {
  26. Configuration = configuration;
  27. }
  28. public IConfiguration Configuration { get; }
  29. // This method gets called by the runtime. Use this method to add services to the container.
  30. public void ConfigureServices(IServiceCollection services)
  31. {
  32. services.AddControllers();
  33. services.AddSwaggerGen(c =>
  34. {
  35. c.SwaggerDoc("v1", new OpenApiInfo { Title = "Hangfire", Version = "v1" });
  36. });
  37. #region Configure Connection String
  38. services.AddDbContext<EmployeeDbContext>(item => item.UseSqlServer(Configuration.GetConnectionString("myconn")));
  39. #endregion
  40. #region Configure Hangfire
  41. services.AddHangfire(c => c.UseSqlServerStorage(Configuration.GetConnectionString("myconn")));
  42. GlobalConfiguration.Configuration.UseSqlServerStorage(Configuration.GetConnectionString("myconn")).WithJobExpirationTimeout(TimeSpan.FromDays(7));
  43. #endregion
  44. #region Services Injection
  45. services.AddTransient<IEmployeeService, EmployeeService>();
  46. #endregion
  47. }
  48. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  49. public void Configure(IApplicationBuilder app, IWebHostEnvironment env,IBackgroundJobClient backgroundJobClient, IRecurringJobManager recurringJobManager)
  50. {
  51. if (env.IsDevelopment())
  52. {
  53. app.UseDeveloperExceptionPage();
  54. app.UseSwagger();
  55. app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Hangfire v1"));
  56. }
  57. #region Configure Hangfire
  58. app.UseHangfireServer();
  59. //Basic Authentication added to access the Hangfire Dashboard
  60. app.UseHangfireDashboard("/hangfire", new DashboardOptions()
  61. {
  62. AppPath = null,
  63. DashboardTitle = "Hangfire Dashboard",
  64. Authorization = new[]{
  65. new HangfireCustomBasicAuthenticationFilter{
  66. User = Configuration.GetSection("HangfireCredentials:UserName").Value,
  67. Pass = Configuration.GetSection("HangfireCredentials:Password").Value
  68. }
  69. },
  70. //Authorization = new[] { new DashboardNoAuthorizationFilter() },
  71. //IgnoreAntiforgeryToken = true
  72. }); ;
  73. #endregion
  74. app.UseHttpsRedirection();
  75. app.UseRouting();
  76. app.UseAuthorization();
  77. app.UseEndpoints(endpoints =>
  78. {
  79. endpoints.MapControllers();
  80. });
  81. #region Job Scheduling Tasks
  82. //recurringJobManager.AddOrUpdate("Insert Employee : Runs Every 1 Min", () => jobscheduler.JobAsync(), "*/1 * * * *");
  83. #endregion
  84. }
  85. }
  86. }
Then we have to create the table using the below migration commands in the package manager console.
Creates migration folder and migration script inside the target project.
  1. PM> Add-Migration 'MigrationName'
The next command executes the migration script and creates a table in the database
  1. PM> Update-Database
Services
EmployeeService.cs
  1. using Hangfire.AppDbContext;
  2. using Hangfire.Model;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Threading.Tasks;
  7. namespace Hangfire.Services
  8. {
  9. public class EmployeeService : IEmployeeService
  10. {
  11. #region Property
  12. private readonly EmployeeDbContext _employeeDbContext;
  13. #endregion
  14. #region Constructor
  15. public EmployeeService(EmployeeDbContext employeeDbContext)
  16. {
  17. _employeeDbContext = employeeDbContext;
  18. }
  19. #endregion
  20. #region Insert Employee
  21. public async Task<bool> InsertEmployeeAsync()
  22. {
  23. try
  24. {
  25. Employee employee = new Employee()
  26. {
  27. EmployeeName = "Jk",
  28. Designation = "Full Stack Developer"
  29. };
  30. await _employeeDbContext.AddAsync(employee);
  31. await _employeeDbContext.SaveChangesAsync();
  32. return true;
  33. }
  34. catch (Exception ex)
  35. {
  36. throw;
  37. }
  38. }
  39. #endregion
  40. }
  41. }
IEmployeeService.cs
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. namespace Hangfire.Services
  6. {
  7. public interface IEmployeeService
  8. {
  9. Task<bool> InsertEmployeeAsync();
  10. }
  11. }
The Service Injection is already done in the Startup. cs file
  1. services.AddTransient<IEmployeeService, EmployeeService>();

Secure the Hangfire Dashboard

To Secure the hangfire dashboard we setup login authentication in order to access the hangfire dashboard. I have hardcoded the username and password in the appsettings.js file to consume those in the startup.cs
appsettings.js
  1. "HangfireCredentials": {
  2. "UserName": "admin",
  3. "Password": "admin@123"
  4. }
Starup.cs
  1. //Basic Authentication added to access the Hangfire Dashboard
  2. app.UseHangfireDashboard("/hangfire", new DashboardOptions()
  3. {
  4. AppPath = null,
  5. DashboardTitle = "Hangfire Dashboard",
  6. Authorization = new[]{
  7. new HangfireCustomBasicAuthenticationFilter{
  8. User = Configuration.GetSection("HangfireCredentials:UserName").Value,
  9. Pass = Configuration.GetSection("HangfireCredentials:Password").Value
  10. }
  11. },
  12. }); ;

Hangfire Retention Time

Usually, the hangfire jobs running in the background will elapse for 24 hours. To avoid this I have to enable the basic setting to last this job in the dashboard for at least 1 week.
Startup.cs
  1. GlobalConfiguration.Configuration.UseSqlServerStorage(Configuration.GetConnectionString("myconn")).WithJobExpirationTimeout(TimeSpan.FromDays(7));

Persistence with SQL Database

Hangfire has an option to store all the job-related information in the database. For this we don't need anything we have to configure this setup in the Startup.cs and it automatically creates all the tables where we can see the job status and respective information in those tables.
Startup.cs
  1. services.AddHangfire(c => c.UseSqlServerStorage(Configuration.GetConnectionString("myconn")));
The above set of tables were created automatically when we configured the setup and point to the database.
Create background tasks
Job.cs
  1. using Hangfire.Services;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. namespace Hangfire
  7. {
  8. public class Job
  9. {
  10. #region Property
  11. private readonly IEmployeeService _employeeService;
  12. #endregion
  13. #region Constructor
  14. public Job(IEmployeeService employeeService)
  15. {
  16. _employeeService = employeeService;
  17. }
  18. #endregion
  19. #region Job Scheduler
  20. public async Task<bool> JobAsync()
  21. {
  22. var result = await _employeeService.InsertEmployeeAsync();
  23. return true;
  24. }
  25. #endregion
  26. }
  27. }
There are 4 types of jobs that mostly we will use. I have created all 4 jobs in a startup.cs file.
Starup.cs
  1. #region Job Scheduling Tasks
  2. // Recurring Job for every 5 min
  3. recurringJobManager.AddOrUpdate("Insert Employee : Runs Every 1 Min", () => jobscheduler.JobAsync(), "*/5 * * * *");
  4. //Fire and forget job
  5. var jobId = backgroundJobClient.Enqueue(() => jobscheduler.JobAsync());
  6. //Continous Job
  7. backgroundJobClient.ContinueJobWith(jobId, () => jobscheduler.JobAsync());
  8. //Schedule Job / Delayed Job
  9. backgroundJobClient.Schedule(() => jobscheduler.JobAsync(), TimeSpan.FromDays(5));
  10. #endregion
Recurring job - Every 5 minutes the background task runs and inserts data into database.
Fire and Forget - This job runs only once when we run the application.
Continuous Job - When we want to run jobs one after another at that time this will be useful so that it will execute one by one.
Schedule Job - If you want to schedule a task to run at a particular time.
Run the application
By default, the swagger endpoint will open. Now type hangfire in the URL by removing the swagger. It will ask for a username and password as we had already set up the authentication mechanism .
If you try to access without login.
If you click on jobs and succeed then we will see the job execution status and its time, and also we can see the historical graph in the dashboard as well.
We can see our scheduled jobs and recurring jobs in the tab and menu and also we have an option to delete the particular job that you no longer want to see.
Download the Source Code - GitHub
I hope this article helps you in creating background tasks as easily as possible!
Keep learning !!!!!!!