Hangfire is an open source task scheduling framework for .NET that allows developers to easily separate long-running tasks, timed tasks, and other background processing from the main thread to improve application responsiveness and performance
1. Install Hangfire
First, you need a Core project. Install Hangfire via NuGet:
Install-Package Hangfire
Also, install Hangfire's supported database drivers, such as SQL Server or Redis, as needed.
2. Configuring Hangfire
exist file to configure Hangfire:
public void ConfigureServices(IServiceCollection services)
{
// Add the Hangfire service and configure it to use SQL Server as the persistence store
(x => ("connection_string"))); // Add the Hangfire server, the core service that handles tasks in the background.
// Add the Hangfire server, the core service that handles tasks in the background.
(); // Add the Hangfire server, the core service that handles tasks in the background.
}
public void Configure(IApplicationBuilder app, IBackgroundJobClient backgroundJobs)
{
// Use the Hangfire Dashboard to allow viewing the execution of the task in the browser
().
// Create a background task of type Fire-and-forget, i.e. execute it once immediately
(() => ("Hello Hangfire!")); // Create a background task of type Fire-and-forget, i.e. execute it immediately.
}
3. Hangfire task types
- Immediate tasks (Fire-and-forget):
var backgroundJobs = <IBackgroundJobClient>();
// Parsing the service and using it
// Create a background job of type Fire-and-forget, i.e., execute it once immediately
(() =>
("Hello Hangfire!,background task, i.e. execute once immediately"));;
- Delayed jobs:
// Delay the task, execute it after 1 minute
(() =>.
("Delay the task, execute in 1 minute"), (1));; // The task is delayed, execute in 1 minute.
(1));
- Recurring jobs:
// Periodic task, executed once a day
("easyjob", () =>.
("Easy!: periodic task, executed once a day"), (
);
//periodic task ,corn expression
("powerfuljob".
() => ("Powerful!, periodic task: execute once per second"), ,
"0/1 * * * * ? "); //Execute once per second [ ]
4. Visit Hangfire Dashboard
();
Once the configuration is complete, you can access thehttp://localhost:5000/hangfire
to view the Hangfire Dashboard and monitor the execution of tasks.
5. Security
In a production environment, you need to set up permission validation for Hangfire Dashboard. This can be done by implementing theIDashboardAuthorizationFilter
interface to customize the authorization logic.
Install-Package
public class BasedAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize([NotNull] context)
{
if ((). ().StartsWith("localhost"))
{
return true; }
}
// Check if the context parameter is null
if (context == null)
{
throw new ArgumentNullException(nameof(context)); }
}
// Get the identity of the user for the current request
var httpContext = (); var authUser = httpContext?
var authUser = httpContext?.User; } // Get the identity of the currently requested user.
// Here you can implement specific authorization logic as needed
// Check if the user is in a certain role, or has a specific permission token
bool isAuthorized = authUser?.Identity?.IsAuthenticated == true
&& ("YourRoleName"); // replace "YourRoleName" with the actual role name
return isAuthorized; }
}
}
("/hangfire", new DashboardOptions
{
Authorization = new List<IDashboardAuthorizationFilter> { new BasedAuthorizationFilter() }
}); // Set the Dashboard URL.
6. Hangfire extension: HttpJob
is an extension component that allows Hangfire to separate task scheduling from business logic. This means that the business logic can be decoupled by exposing it to Hangfire as a separate Web API for scheduling. Here are some key points:
- Project Address: GitHub。
- goalThe Hangfire solution is designed to help business developers ignore Hangfire by stripping away job scheduling and operations, so that different lines of business can deploy job agents independently without affecting each other.
- Technical characteristics: Supports Deferred Tasks, Periodic Tasks, Task Management, Cron Generator, and Task Agent extensions.
- application scenario: For task scheduling in timed tasks, background jobs, periodic tasks, and microservice architectures.
7. Other resources
- Official website address:Hangfire Documentation
- GitHub source code:HangfireIO/Hangfire
- Chinese Documentation:Hangfire-zh-official
Welcome to follow my public number "Net share", technical articles first time push, as the case may be updated , share some of the details you may not notice.