Hangfire .NET Core(開發者的工作原理)
現代應用程式開發通常需要處理背景任務,以處理龐大的工作量。 在這種情況下,我們需要能夠執行多個工作的背景工作處理程式。 C# .NET Core 應用程式的背景工作處理程式就是其中之一,它就是 Hangfire。在本篇博客中,我們將學習如何管理 Hangfire 背景作業,以及如何與其他套件搭配使用,例如 IronPDF for PDF Generation 以在背景中產生 PDF 文件。
Hangfire 透過提供可靠且彈性的框架來管理和執行背景工作,簡化了 ASP.NET Core 或 .NET Core 6 Web API 應用程式中背景處理的執行。 Hangfire 以 NuGet 套件的形式提供,可使用 .NET CLI 安裝,如下所示:
dotnet add package Hangfire --version 1.8.6
在 .NET Core Web API 中實作。
要了解 Hangfire,讓我們建立一個簡單的 .NET Core API 應用程式,並使用 CLI 安裝 Hangfire。
dotnet new webapi -n HangfireDemo
cd HangfireDemo
dotnet build
dotnet add package Hangfire --version 1.8.6
dotnet builddotnet new webapi -n HangfireDemo
cd HangfireDemo
dotnet build
dotnet add package Hangfire --version 1.8.6
dotnet build在此,我們使用 .NET CLI 建立一個簡單的天氣 REST API。 第一行建立一個名為 HangfireDemo 的 .NET Core Web API 專案,以執行 API 端點。 第二行會導航到我們新建立的資料夾"HangfireDemo",然後建立專案。 接下來,我們將 Hangfire NuGet 套件加入專案,並再次建立專案。 之後,您可以在您選擇的任何編輯器中開啟專案,例如 Visual Studio 2022 或 JetBrains Rider。 現在如果您執行專案,可以看到 Swagger 如下所示:

這裡我們可以看到天氣 GET API,它會回傳日期、摘要和溫度。

現在讓我們加入 Hangfire 背景工作處理器。 在 Visual Studio 中開啟專案。
新增 Hangfire 工作處理器
在您的應用程式中設定 Hangfire,通常是在 Startup.cs 檔案中。這包括設定工作儲存空間和初始化 Hangfire 伺服器。
// Startup.cs
using Hangfire;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Add Hangfire services and use SQL Server as storage option
services.AddHangfire(config => config.UseSqlServerStorage("your_connection_string"));
services.AddHangfireServer();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Use Hangfire Server and Dashboard for monitoring and managing jobs
app.UseHangfireServer();
app.UseHangfireDashboard();
// Your other configuration settings
}
}// Startup.cs
using Hangfire;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Add Hangfire services and use SQL Server as storage option
services.AddHangfire(config => config.UseSqlServerStorage("your_connection_string"));
services.AddHangfireServer();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Use Hangfire Server and Dashboard for monitoring and managing jobs
app.UseHangfireServer();
app.UseHangfireDashboard();
// Your other configuration settings
}
}' Startup.cs
Imports Hangfire
Public Class Startup
Public Sub ConfigureServices(ByVal services As IServiceCollection)
' Add Hangfire services and use SQL Server as storage option
services.AddHangfire(Function(config) config.UseSqlServerStorage("your_connection_string"))
services.AddHangfireServer()
End Sub
Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IHostingEnvironment)
' Use Hangfire Server and Dashboard for monitoring and managing jobs
app.UseHangfireServer()
app.UseHangfireDashboard()
' Your other configuration settings
End Sub
End ClassConfigureServices 方法用來新增儲存空間,以儲存 Hangfire 新建立的工作。 這裡使用的是 SQL Server 資料庫。 SQL Server 連接字串應以 "your_connection_string" 取代。 人們也可以使用 Hangfire.InMemory 的記憶體儲存。
dotnet add package Hangfire.InMemory --version 0.6.0
並取代為
services.AddHangfire(configuration => { configuration.UseInMemoryStorage(); });services.AddHangfire(configuration => { configuration.UseInMemoryStorage(); });services.AddHangfire(Sub(configuration)
configuration.UseInMemoryStorage()
End Sub)建立背景工作。
定義您希望作為背景工作執行的方法。 這些方法應該是靜態或具有無參數構造器類的實例方法。 工作可以以經常性工作的方式執行,也可以同時執行多個工作。
public class MyBackgroundJob
{
public void ProcessJob()
{
// Background job logic, can be a recurring job or multiple jobs
Console.WriteLine("Background job is running...");
}
}public class MyBackgroundJob
{
public void ProcessJob()
{
// Background job logic, can be a recurring job or multiple jobs
Console.WriteLine("Background job is running...");
}
}Public Class MyBackgroundJob
Public Sub ProcessJob()
' Background job logic, can be a recurring job or multiple jobs
Console.WriteLine("Background job is running...")
End Sub
End ClassEnqueue Jobs
使用 Hangfire API 匯入背景工作。 您可以排程背景工作在特定時間、延遲後或定期執行。
// Enqueue a job to run immediately
BackgroundJob.Enqueue<MyBackgroundJob>(x => x.ProcessJob());
// Schedule a job to run after a 5-minute delay
BackgroundJob.Schedule<MyBackgroundJob>(x => x.ProcessJob(), TimeSpan.FromMinutes(5));
// Schedule a recurring job using a job ID
RecurringJob.AddOrUpdate<MyBackgroundJob>("jobId", x => x.ProcessJob(), Cron.Daily);// Enqueue a job to run immediately
BackgroundJob.Enqueue<MyBackgroundJob>(x => x.ProcessJob());
// Schedule a job to run after a 5-minute delay
BackgroundJob.Schedule<MyBackgroundJob>(x => x.ProcessJob(), TimeSpan.FromMinutes(5));
// Schedule a recurring job using a job ID
RecurringJob.AddOrUpdate<MyBackgroundJob>("jobId", x => x.ProcessJob(), Cron.Daily);' Enqueue a job to run immediately
BackgroundJob.Enqueue(Of MyBackgroundJob)(Function(x) x.ProcessJob())
' Schedule a job to run after a 5-minute delay
BackgroundJob.Schedule(Of MyBackgroundJob)(Function(x) x.ProcessJob(), TimeSpan.FromMinutes(5))
' Schedule a recurring job using a job ID
RecurringJob.AddOrUpdate(Of MyBackgroundJob)("jobId", Function(x) x.ProcessJob(), Cron.Daily)Hangfire Dashboard 和 Server
可在 Configure 方法中加入 Hangfire 面板和伺服器,以進行即時工作監控。
// Run Hangfire server and dashboard
app.UseHangfireServer();
app.UseHangfireDashboard();// Run Hangfire server and dashboard
app.UseHangfireServer();
app.UseHangfireDashboard();' Run Hangfire server and dashboard
app.UseHangfireServer()
app.UseHangfireDashboard()伺服器也可以在 ConfigureServices 中加入。
services.AddHangfireServer();services.AddHangfireServer();services.AddHangfireServer()Fire and Forget Jobs
// Fire and forget jobs are executed only once and almost immediately after creation.
var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget!")); // Job ID for fire and forget job// Fire and forget jobs are executed only once and almost immediately after creation.
var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget!")); // Job ID for fire and forget job' Fire and forget jobs are executed only once and almost immediately after creation.
Dim jobId = BackgroundJob.Enqueue(Sub() Console.WriteLine("Fire-and-forget!")) ' Job ID for fire and forget job經常性工作
// Recurring jobs fire many times based on a specified CRON schedule.
RecurringJob.AddOrUpdate("myrecurringjob", () => Console.WriteLine("Recurring!"), Cron.Daily);// Recurring jobs fire many times based on a specified CRON schedule.
RecurringJob.AddOrUpdate("myrecurringjob", () => Console.WriteLine("Recurring!"), Cron.Daily);' Recurring jobs fire many times based on a specified CRON schedule.
RecurringJob.AddOrUpdate("myrecurringjob", Sub() Console.WriteLine("Recurring!"), Cron.Daily)延遲的工作
// Delayed jobs are executed only once but after a specified interval.
var jobId = BackgroundJob.Schedule(() => Console.WriteLine("Delayed!"), TimeSpan.FromDays(7));// Delayed jobs are executed only once but after a specified interval.
var jobId = BackgroundJob.Schedule(() => Console.WriteLine("Delayed!"), TimeSpan.FromDays(7));' Delayed jobs are executed only once but after a specified interval.
Dim jobId = BackgroundJob.Schedule(Sub() Console.WriteLine("Delayed!"), TimeSpan.FromDays(7))續篇
// Continuation jobs are executed once their parent jobs have completed.
BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine("Continuation!"));// Continuation jobs are executed once their parent jobs have completed.
BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine("Continuation!"));' Continuation jobs are executed once their parent jobs have completed.
BackgroundJob.ContinueJobWith(jobId, Sub() Console.WriteLine("Continuation!"))批量工作
// Batch is a group of background jobs created atomically and considered as a single entity.
var batchId = BatchJob.StartNew(x =>
{
x.Enqueue(() => Console.WriteLine("Job 1"));
x.Enqueue(() => Console.WriteLine("Job 2"));
});// Batch is a group of background jobs created atomically and considered as a single entity.
var batchId = BatchJob.StartNew(x =>
{
x.Enqueue(() => Console.WriteLine("Job 1"));
x.Enqueue(() => Console.WriteLine("Job 2"));
});' Batch is a group of background jobs created atomically and considered as a single entity.
Dim batchId = BatchJob.StartNew(Sub(x)
x.Enqueue(Sub() Console.WriteLine("Job 1"))
x.Enqueue(Sub() Console.WriteLine("Job 2"))
End Sub)批次延續工作
// Batch continuation is fired when all background jobs in a parent batch are finished.
BatchJob.ContinueBatchWith(batchId, x =>
{
x.Enqueue(() => Console.WriteLine("Last Job"));
});// Batch continuation is fired when all background jobs in a parent batch are finished.
BatchJob.ContinueBatchWith(batchId, x =>
{
x.Enqueue(() => Console.WriteLine("Last Job"));
});' Batch continuation is fired when all background jobs in a parent batch are finished.
BatchJob.ContinueBatchWith(batchId, Sub(x)
x.Enqueue(Sub() Console.WriteLine("Last Job"))
End Sub)儀表板
Hangfire Dashboard 是您可以找到所有背景工作資訊的地方。 它是以 OWIN 中介軟體的方式寫成 (如果您不熟悉 OWIN,也不用擔心),因此您可以將它插入 ASP.NET、ASP.NET MVC、Nancy 和 ServiceStack 應用程式中,也可以使用 OWIN Self-Host 功能將 Dashboard 寄存在 Console Applications 或 Windows Services 內。
當您啟用儀表板時,可在 /hangfire/ 延伸欄位取得。 在此儀表板中,您可以管理背景執行中的工作、排程背景工作,並檢視"啟動與遺忘"工作以及重複性工作。 這些工作可以使用工作 ID 來識別。
即時處理

成功的工作
檢視以下成功的工作。

排程工作

當您的應用程式執行時,Hangfire 會根據設定來處理背景工作。
請記得查看 Hangfire 文件,以瞭解更多進階的設定選項和功能:Hangfire Documentation 和完整程式碼可在 GitHub Hangfire Demo 上找到。
介紹 IronPDF。
IronPDF for .NET PDF Generation 是 Iron Software 的 PDF Library 中的 NuGet 套件,可協助讀取和產生 PDF 文件。 它可以將格式簡單、包含樣式資訊的文件轉換成 PDF。 IronPDF 可以輕鬆地從 HTML 內容產生 PDF。 它可以從 URL 下載 HTML,然後產生 PDF。
IronPdf 的主要魅力在於它的 HTML 至 PDF 轉換功能,可保留版面與樣式。 它可以從網頁內容建立 PDF,是報告、發票和文件的理想選擇。 此功能支援將 HTML 檔案、URL 和 HTML 字串轉換為 PDF。
using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}using IronPdf;
class Program
{
static void Main(string[] args)
{
var renderer = new ChromePdfRenderer();
// Convert HTML String to PDF
var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
// Convert HTML File to PDF
var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
// Convert URL to PDF
var url = "http://ironpdf.com"; // Specify the URL
var pdfFromUrl = renderer.RenderUrlAsPdf(url);
pdfFromUrl.SaveAs("URLToPDF.pdf");
}
}Imports IronPdf
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim renderer = New ChromePdfRenderer()
' Convert HTML String to PDF
Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")
' Convert HTML File to PDF
Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")
' Convert URL to PDF
Dim url = "http://ironpdf.com" ' Specify the URL
Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
pdfFromUrl.SaveAs("URLToPDF.pdf")
End Sub
End Class開始使用 IronPDF
安裝 IronPdf Library
使用 NuGet 套件管理員安裝
若要使用 NuGet Package Manager 將 IronPDF 整合至您的 Hangfire .NET 專案,請遵循下列步驟:
1.開啟 Visual Studio,並在"解決方案總管"中,用滑鼠右鍵按一下專案。 2.從上下文功能表中選擇"管理 NuGet 套件..."。 3.前往瀏覽索引標籤,搜尋 IronPdf。 4.從搜尋結果中選擇 IronPDF 函式庫,然後按一下安裝按鈕。 5.接受任何許可協議提示。
如果您偏好使用套件管理員控制台,請執行下列指令:
Install-Package IronPdf
這將取得 IronPDF 並將其安裝到您的專案中。
使用 NuGet 網站安裝
如需 IronPDF 的詳細概述,包括功能、相容性和其他下載選項,請造訪 NuGet 網站上的 IronPDF 頁面,網址為 https://www.nuget.org/packages/IronPdf。
透過 DLL 安裝
另外,您也可以使用 IronPDF 的 DLL 檔案,直接將 IronPDF 納入您的專案中。從此 IronPDF Direct Download 下載包含 DLL 的 ZIP 檔案。 解壓縮,並將 DLL 包含在您的專案中。
現在讓我們修改應用程式,加入背景處理工作,將網站下載為 PDF 檔案。
namespace HangfireDemo.Core;
public class PdfGenerationJob
{
public void Start(string website)
{
// Create a PDF from any existing web page
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderUrlAsPdf(website);
var filePath = AppContext.BaseDirectory + "result.pdf";
pdf.SaveAs(filePath);
}
}namespace HangfireDemo.Core;
public class PdfGenerationJob
{
public void Start(string website)
{
// Create a PDF from any existing web page
ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderUrlAsPdf(website);
var filePath = AppContext.BaseDirectory + "result.pdf";
pdf.SaveAs(filePath);
}
}Namespace HangfireDemo.Core
Public Class PdfGenerationJob
Public Sub Start(ByVal website As String)
' Create a PDF from any existing web page
Dim renderer As New ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderUrlAsPdf(website)
Dim filePath = AppContext.BaseDirectory & "result.pdf"
pdf.SaveAs(filePath)
End Sub
End Class
End NamespaceIronPDF 內建了從 URL 下載網站並儲存為 PDF 文件的方法。 我們要在工作中使用此方法下載並儲存至指定位置。 此背景工作可修改為取得多個網站 URL 並將其儲存為 PDF。
現在,讓我們新增一個控制器,以揭露 PDF 生成和下載 API。
using Hangfire;
using HangfireDemo.Core;
using Microsoft.AspNetCore.Mvc;
namespace HangfireDemo.Controllers;
[ApiController]
[Route("[controller]")]
public class PdfGeneratorController : ControllerBase
{
[HttpGet("request", Name = "Start PDF Generation")]
public void Start([FromQuery] string websiteUrl)
{
BackgroundJob.Enqueue<PdfGenerationJob>(x => x.Start(websiteUrl));
}
[HttpGet("result", Name = "Download PDF Generation")]
public IActionResult WebResult()
{
var filePath = AppContext.BaseDirectory + "result.pdf";
var stream = new FileStream(filePath, FileMode.Open);
return new FileStreamResult(stream, "application/octet-stream") { FileDownloadName = "website.pdf" };
}
}using Hangfire;
using HangfireDemo.Core;
using Microsoft.AspNetCore.Mvc;
namespace HangfireDemo.Controllers;
[ApiController]
[Route("[controller]")]
public class PdfGeneratorController : ControllerBase
{
[HttpGet("request", Name = "Start PDF Generation")]
public void Start([FromQuery] string websiteUrl)
{
BackgroundJob.Enqueue<PdfGenerationJob>(x => x.Start(websiteUrl));
}
[HttpGet("result", Name = "Download PDF Generation")]
public IActionResult WebResult()
{
var filePath = AppContext.BaseDirectory + "result.pdf";
var stream = new FileStream(filePath, FileMode.Open);
return new FileStreamResult(stream, "application/octet-stream") { FileDownloadName = "website.pdf" };
}
}Imports Hangfire
Imports HangfireDemo.Core
Imports Microsoft.AspNetCore.Mvc
Namespace HangfireDemo.Controllers
<ApiController>
<Route("[controller]")>
Public Class PdfGeneratorController
Inherits ControllerBase
<HttpGet("request", Name := "Start PDF Generation")>
Public Sub Start(<FromQuery> ByVal websiteUrl As String)
BackgroundJob.Enqueue(Of PdfGenerationJob)(Function(x) x.Start(websiteUrl))
End Sub
<HttpGet("result", Name := "Download PDF Generation")>
Public Function WebResult() As IActionResult
Dim filePath = AppContext.BaseDirectory & "result.pdf"
Dim stream = New FileStream(filePath, FileMode.Open)
Return New FileStreamResult(stream, "application/octet-stream") With {.FileDownloadName = "website.pdf"}
End Function
End Class
End Namespace在此我們建立了兩個 API:一個用來啟動背景工作並取得網站 URL 以啟動下載,另一個 API 則用來下載結果 PDF。 API 的描述如下所示。

結果是這樣的

授權(可免費試用)
若要使上述程式碼在沒有水印的情況下運作,必須取得授權金鑰。 開發人員註冊IronPDF免費試用後,即可獲得試用授權。 試用授權不需要信用卡。 您可以提供您的電子郵件 ID 並註冊免費試用。
結論
Hangfire 和 IronPDF 在一起是在背景中生成和下載 PDF 的絕佳組合。 Hangfire 可以高效處理長時間執行的任務,而 IronPDF 則為 PDF 生成提供了靈活易用的解決方案。 要瞭解有關 IronPdf 的更多資訊,您可以造訪 IronPDF說明文件。
此外,還可探索 Iron Software 產品套件中的其他工具,這些工具可提升您的編碼技巧並滿足現代應用程式的需求。
常見問題解答
什麼是 .NET Core 中的 Hangfire?
Hangfire 是一個框架,可簡化 ASP.NET Core 或 .NET Core 6 應用程式中背景處理的實作。它為管理和執行背景工作提供了可靠且彈性的解決方案。
如何在 .NET Core 應用程式中安裝 Hangfire?
Hangfire 可以作為 NuGet 套件安裝。您可以使用 .NET CLI 以下列指令新增它:dotnet add package Hangfire --version 1.8.6。
Hangfire 支援哪些類型的背景工作?
Hangfire 支援各種類型的背景作業,包括 Fire-and-forget 作業、延遲作業、重複作業和延續作業。
如何在 .NET Core 應用程式中設定 Hangfire?
Hangfire 是在 Startup.cs 檔案中設定的,您可在此設定工作儲存並初始化 Hangfire 伺服器。這通常涉及新增 Hangfire 服務,以及設定 SQL Server 或記憶體儲存空間。
什麼是 Hangfire Dashboard?
Hangfire Dashboard 是監控和管理背景工作的工具。它提供有關即時處理、已完成工作和排程工作的資訊,並可透過網頁介面存取。
如何使用 Hangfire 建立背景工作?
可以使用 Hangfire 來建立背景工作,方法是先定義要執行工作的方法,然後再使用 Hangfire API 來排程。工作可以排程為立即執行、延遲執行或循環執行。
如何使用 .NET Core 在背景中執行 PDF 生成任務?
您可以使用支援 HTML 至 PDF 轉換的 PDF 函式庫,在背景執行 PDF 產生任務。這可以整合到像 Hangfire 之類的背景作業處理框架中,從 HTML 內容自動建立 PDF。
.NET 中的 PDF 生成庫有哪些功能?
PDF 生成庫可以將 HTML 字串、HTML 檔案和 URL 轉換為 PDF。它可以保留版面和樣式,對於從網頁內容產生報告、發票和文件非常有用。
如何在 .NET 專案中安裝 PDF 產生函式庫?
PDF 產生函式庫可以使用 Visual Studio 中的 NuGet 套件管理員或透過套件管理員控制台的特定指令來安裝。也可以直接從函式庫的網站下載 DLL 來安裝。
使用無水印 PDF 生成庫需要哪些條件?
若要使用沒有水印的 PDF 產生函式庫,通常需要授權金鑰。在函式庫網站上註冊後,可以獲得免費的試用授權。
如何在 .NET Core 中將 PDF 生成工具與 Hangfire 整合?
您可以在 .NET Core 中將 PDF 生成工具與 Hangfire 整合,方法是設定一個使用 PDF 生成函式庫將 HTML 轉換為 PDF 的背景作業。這樣就可以在應用程式中自動建立和管理文件。







