Implement Hangfire With ASP .NET Core
- Hangfire is open-source and used to schedule the job at a particular event and time.
- It is also, uses to create, process, and manage your background jobs.
- Basically, 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 monitor and manage all things easily.
Why Hangfire is required in Background Processing
- Sometimes we need to do lengthy operations like database updates and database maintenance and managed things on periodically basis.
- Batch import from XML, JSON, and YAML files.
- Recurring reports periodically basis.
- Mass Notification on Subscription, Sign up basis.
So, these are things which we are able to do periodically over a certain period of time as per our requirement.
Prerequisites
Basic understanding of .NET Core API and C#.
Visual Studio 2019 or above
SQL Server
In this article I am implementing Recurring Job:
Recurring Job is executed many times after specified conditions and time interval
Step 1: Install Hangfire NuGet Package.
Step 2 : Make Service Class for Recuring Job.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Extensions.Configuration;
using SalesPulse.DAL;
using SalesPulse.Domain;
namespace SalesPulse.Service
{
public class BackGroundJobService : IBackGroundJobService
{
private readonly IConfiguration _config;
private readonly IBaseRepository<Thana> _thanaRepository;
private readonly IUnitOfWork _unitOfWork;
public BackGroundJobService(IConfiguration config, IBaseRepository<Thana> thanaRepository, IUnitOfWork unitOfWork)
{
_config = config;
_thanaRepository = thanaRepository;
_unitOfWork = unitOfWork;
}
private string GenerateRandomString()
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
return new string(Enumerable.Repeat(chars, 10)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
private string GenerateRandomCode()
{
Random random = new Random();
return $"Code_{random.Next(1000, 9999)}";
}
public void AddThana()
{
var thana = new Thana();
thana.Name = GenerateRandomString();
thana.Code = GenerateRandomCode();
_thanaRepository.Add(thana);
_unitOfWork.Commit();
}
}
}
Implement service class in interface
using System;
using System.Collections.Generic;
using System.Text;
namespace SalesPulse.Service
{
public interface IBackGroundJobService
{
void AddThana();
}
}
Step 3 : Finally, Let’s configure things in startup.css Class related to Hangfire like SQL Server Database and middleware which we need.
//hangfire
var connectionString = Configuration.GetConnectionString("DatabaseConnection");
services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_170).UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings().UseSqlServerStorage(connectionString, new SqlServerStorageOptions
{
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
DisableGlobalLocks = true
}));
services.AddHangfireServer();
//hangfire
app.UseHangfireDashboard();
RecurringJob.AddOrUpdate<IBackGroundJobService>("add Thana", service=>service.AddThana(),Cron.Minutely);
Now run the API and view hangfire dashborad using /hangfire endpoint.
Here you can see how recurring job is 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