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 build
dotnet 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 Class
ConfigureServices方法用於新增儲存以保存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 Class
加入任務
使用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儀表板和伺服器
可以在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 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儀表板是您可以找到所有關於背景任務的資訊的地方。 它是作為OWIN中介軟體編寫的(如果您不熟悉OWIN,不用擔心),因此您可以將其插入到您的ASP.NET、ASP.NET MVC、Nancy和ServiceStack應用程式中,還可以使用OWIN自我託管功能將儀表板託管在控制台應用程式或Windows服務中。
當您啟用儀表板時,它會在/hangfire/ 擴展名處可用。 在此儀表板中,您可以管理背景運行任務,安排背景任務,並查看即拋即棄任務以及週期性任務。 任務可以使用任務ID識別。
實時處理

成功任務
請查看下方的成功任務。

排定的任務

當您的應用程式運行時,Hangfire將根據配置設置負責處理背景任務。
請記住查閱Hangfire文件以獲取更多高級配置選項和功能:Hangfire文件及完整程式碼可以在GitHub Hangfire範例找到。
介紹IronPDF
IronPDF for .NET PDF Generation是NuGet包,來自Iron Software的PDF程式庫,幫助讀取和生成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程式庫
使用NuGet Package Manager安裝
要將IronPDF整合到您的Hangfire .NET專案中,請按照這些步驟使用NuGet Package Manager:
- 打開Visual Studio,在解決方案總管中右鍵單擊您的專案。
- 從上下文選單中選擇"管理NuGet包..."。
- 轉到瀏覽標籤,搜索IronPDF。
- 從搜索結果中選擇IronPDF程式庫並單擊安裝按鈕。
- 接受任何授權協議提示。
如果您更喜歡使用Package Manager Console,執行以下命令:
Install-Package IronPdf
這將獲取並將IronPDF安裝到您的專案中。
使用NuGet網站安裝
要詳細了解IronPDF的功能、相容性和其他下載選項,請存取NuGet網站上的IronPDF頁面,網址為https://www.nuget.org/packages/IronPdf。
通過DLL安裝
或者,您可以直接使用其DLL文件將IronPDF整合到您的專案中。從這個IronPDF直接下載下載包含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 Namespace
IronPDF具有內建的方法,可以從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支持各種型別的背景作業,包括一次性作業、延遲作業、定期作業和後續作業。
您如何在.NET Core應用程式中配置Hangfire?
Hangfire在Startup.cs文件中配置,您可在此設置作業儲存和初始化Hangfire伺服器。通常涉及新增Hangfire服務和設置SQL Server或記憶體儲存。
什麼是Hangfire Dashboard?
Hangfire Dashboard是一個用於監控和管理背景作業的工具。它提供有關即時處理、成功作業和計劃作業的資訊,並可通過Web介面存取。
您如何使用Hangfire建立背景作業?
可以使用Hangfire定義您要作為作業運行的方法,然後使用Hangfire API將其排入隊列來建立背景作業。作業可以立即、延遲或定期運行。
如何在.NET Core中在背景執行PDF生成任務?
您可以使用支持HTML到PDF轉換的PDF庫在背景執行PDF生成任務。這可以整合到像Hangfire這樣的背景作業處理框架中,以自動化從HTML內容建立PDF。
PDF生成庫在.NET中的一些功能是什麼?
PDF生成庫能將HTML字串、HTML文件和URL轉換為PDF。它保留佈局和樣式,非常適合從Web內容生成報告、發票和文件。
如何在.NET專案中安裝PDF生成庫?
PDF生成庫可使用Visual Studio中的NuGet套件管理器或通過Package Manager Console使用特定命令進行安裝。也可以直接從庫網站下載DLL進行安裝。
使用不帶浮水印的PDF生成庫需要什麼?
通常需要許可金鑰來使用不帶浮水印的PDF生成庫。可在註冊庫網站後獲取免費試用許可。
如何將PDF生成工具與Hangfire在.NET Core中整合?
可以在.NET Core中設置一個使用PDF生成庫將HTML轉換為PDF的背景作業來整合PDF生成工具和Hangfire。這允許在應用程式中自動化文件建立和管理。




