.NET 幫助

Hangfire .NET Core(對開發人員的運作方式)

Chipego
奇佩戈·卡林达
2024年1月14日
分享:

現代應用程式開發經常需要處理背景任務以處理龐大的任務,在這種情境下,我們需要背景任務處理器來執行多個工作。 有許多工作處理器,其中一個用於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

在這裡,我們正在使用 .NET CLI 創建一個簡單的天氣 REST API。 第一行創建了一個名為 HangfireDemo 的 Core Web API 專案(也可以創建 ASP.NET Core)以執行 API 端點。 第二行是導航到我們新創建的文件夾“HangfireDemo”,然後構建項目。 接下來,我們將 Hangfire NuGet 套件添加到我們的項目中,然後再次構建它。 接下來,您可以在任意編輯器中開啟您的專案,例如 Visual Studio 2022 或 JetBrains Rider。 現在如果您運行項目,您可以看到如下的 Swagger。

Hangfire .NET Core (開發人員如何操作): 圖一 - Swagger

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

Hangfire .NET Core(開發人員如何使用):圖 2 - 天氣 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
        services.AddHangfire(config => config.UseSqlServerStorage("your_connection_string"));
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // Configure Hangfire
        app.UseHangfireServer();
        app.UseHangfireDashboard();
        // Your other configuration settings
    }
}
// Startup.cs
using Hangfire;
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Hangfire services
        services.AddHangfire(config => config.UseSqlServerStorage("your_connection_string"));
    }
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // Configure Hangfire
        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
		services.AddHangfire(Function(config) config.UseSqlServerStorage("your_connection_string"))
	End Sub
	Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IHostingEnvironment)
		' Configure Hangfire
		app.UseHangfireServer()
		app.UseHangfireDashboard()
		' Your other configuration settings
	End Sub
End Class
$vbLabelText   $csharpLabel

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)
$vbLabelText   $csharpLabel

創建背景作業

定義您希望作為背景作業運行的方法。 這些方法應該是具有無參數構造函數之類的靜態方法或實例方法。 這些作業可以作為定期作業運行,或者可以運行多個作業。

public class MyBackgroundJob
{
    public void ProcessJob()
    {
        // Your background job logic, recurring job or multiple jobs
        Console.WriteLine("Background job is running...");
    }
}
public class MyBackgroundJob
{
    public void ProcessJob()
    {
        // Your background job logic, recurring job or multiple jobs
        Console.WriteLine("Background job is running...");
    }
}
Public Class MyBackgroundJob
	Public Sub ProcessJob()
		' Your background job logic, recurring job or multiple jobs
		Console.WriteLine("Background job is running...")
	End Sub
End Class
$vbLabelText   $csharpLabel

排入工作隊列

使用 Hangfire API 排隊背景任務。 您可以安排背景工作在特定時間、延遲後或定期運行。

// Enqueue a job to run immediately
BackgroundJob.Enqueue<MyBackgroundJob>(x => x.ProcessJob());
// Schedule a job to run after 5 min delay, delayed job
BackgroundJob.Schedule<MyBackgroundJob>(x => x.ProcessJob(), TimeSpan.FromMinutes(5));
// Schedule a recurring job / recurring jobs using job Id
RecurringJob.AddOrUpdate<MyBackgroundJob>("job Id", x => x.ProcessJob(), Cron.Daily);
// Enqueue a job to run immediately
BackgroundJob.Enqueue<MyBackgroundJob>(x => x.ProcessJob());
// Schedule a job to run after 5 min delay, delayed job
BackgroundJob.Schedule<MyBackgroundJob>(x => x.ProcessJob(), TimeSpan.FromMinutes(5));
// Schedule a recurring job / recurring jobs using job Id
RecurringJob.AddOrUpdate<MyBackgroundJob>("job Id", 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 5 min delay, delayed job
BackgroundJob.Schedule(Of MyBackgroundJob)(Function(x) x.ProcessJob(), TimeSpan.FromMinutes(5))
' Schedule a recurring job / recurring jobs using job Id
RecurringJob.AddOrUpdate(Of MyBackgroundJob)("job Id", Function(x) x.ProcessJob(), Cron.Daily)
$vbLabelText   $csharpLabel

Hangfire 儀表板和伺服器

可以在 Configure 方法中添加 Hangfire 儀表板和伺服器。

// Run Hangfire server
app.UseHangfireServer();
app.UseHangfireDashboard();
// Run Hangfire server
app.UseHangfireServer();
app.UseHangfireDashboard();
' Run Hangfire server
app.UseHangfireServer()
app.UseHangfireDashboard()
$vbLabelText   $csharpLabel

伺服器也可以在 ConfigureServices 中添加。

services.AddHangfireServer();
services.AddHangfireServer();
services.AddHangfireServer()
$vbLabelText   $csharpLabel

無需監控的任務

//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!")); //jobId for Fire and forget job
//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!")); //jobId for Fire and forget job
'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!")) 'jobId for Fire and forget job
$vbLabelText   $csharpLabel

定期工作

//Recurring jobs fire many times on the specified CRON schedule.
RecurringJob.AddOrUpdate( "myrecurringjob",() => Console.WriteLine("Recurring!"),Cron.Daily);
//Recurring jobs fire many times on the specified CRON schedule.
RecurringJob.AddOrUpdate( "myrecurringjob",() => Console.WriteLine("Recurring!"),Cron.Daily);
'Recurring jobs fire many times on the specified CRON schedule.
RecurringJob.AddOrUpdate("myrecurringjob",Sub() Console.WriteLine("Recurring!"),Cron.Daily)
$vbLabelText   $csharpLabel

延遲的工作

//Delayed jobs are executed only once too, but not immediately, after a certain specific interval.
var jobId = BackgroundJob.Schedule(() => Console.WriteLine("Delayed!"),
    TimeSpan.FromDays(7));
//Delayed jobs are executed only once too, but not immediately, after a certain specific interval.
var jobId = BackgroundJob.Schedule(() => Console.WriteLine("Delayed!"),
    TimeSpan.FromDays(7));
'Delayed jobs are executed only once too, but not immediately, after a certain specific interval.
Dim jobId = BackgroundJob.Schedule(Sub() Console.WriteLine("Delayed!"), TimeSpan.FromDays(7))
$vbLabelText   $csharpLabel

延續

//Continuation jobs are executed when its parent job has been finished, immediate child job
BackgroundJob.ContinueJobWith(jobId,() => Console.WriteLine("Continuation!"));
//Continuation jobs are executed when its parent job has been finished, immediate child job
BackgroundJob.ContinueJobWith(jobId,() => Console.WriteLine("Continuation!"));
'Continuation jobs are executed when its parent job has been finished, immediate child job
BackgroundJob.ContinueJobWith(jobId,Sub() Console.WriteLine("Continuation!"))
$vbLabelText   $csharpLabel

批次作業

//Batch is a group of background jobs that is created atomically and considered as a single entity. Two jobs can be run as below.
var batchId = BatchJob.StartNew(x =>
{
    x.Enqueue(() => Console.WriteLine("Job 1"));
    x.Enqueue(() => Console.WriteLine("Job 2"));
});
//Batch is a group of background jobs that is created atomically and considered as a single entity. Two jobs can be run as below.
var batchId = BatchJob.StartNew(x =>
{
    x.Enqueue(() => Console.WriteLine("Job 1"));
    x.Enqueue(() => Console.WriteLine("Job 2"));
});
'Batch is a group of background jobs that is created atomically and considered as a single entity. Two jobs can be run as below.
Dim batchId = BatchJob.StartNew(Sub(x)
	x.Enqueue(Sub() Console.WriteLine("Job 1"))
	x.Enqueue(Sub() Console.WriteLine("Job 2"))
End Sub)
$vbLabelText   $csharpLabel

批次連續作業

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"));
});
Dim tempVar As Boolean = TypeOf continuation Is fired
Dim [when] As fired = If(tempVar, CType(continuation, fired), Nothing)
Batch tempVar all background jobs in a parent batch are finished.BatchJob.ContinueBatchWith(batchId, Sub(x)
	x.Enqueue(Sub() Console.WriteLine("Last Job"))
End Sub)
$vbLabelText   $csharpLabel

儀表板

Hangfire Dashboard 是您可以找到有關背景作業的所有資訊的地方。 它被編寫為 OWIN 中介軟體(如果你不熟悉 OWIN,別擔心),因此你可以將它插入到你的 ASP.NET、ASP.NET MVC、Nancy 和 ServiceStack 應用程序中,並且可以使用OWIN 自我託管功能在控制台應用程序或 Windows 服務中託管儀表板。

當您在視圖中啟用控制台時,控制台位於 /hangfire/ 擴展。 在此儀表板中,可以管理後台執行的工作、排程後台工作、查看即發即忘的工作和定期工作。 這些工作可以使用工作 ID 識別。

即時處理

Hangfire .NET Core(開發人員如何使用):圖3 - 任務的即時處理

成功的工作

成功的任務可以在下方查看。

Hangfire .NET Core(對開發者的工作方式):圖4 - 完成的任務

排程工作

Hangfire .NET Core(如何為開發人員工作):圖5 - 定時作業

現在,當您的應用程序運行時,Hangfire 將根據配置的設置負責處理背景工作。

請記得查看 Hangfire 文檔以獲取更高級的配置選項和功能:Hangfire 文檔 完整代碼可在 GitHub Hangfire 示範 中找到。

介紹 IronPDF

IronPDF for .NET PDF 生成 是一個來自 Iron Software 的 PDF 函式庫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();

        // 1. 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");

        // 2. 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");

        // 3. 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();

        // 1. 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");

        // 2. 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");

        // 3. 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()

		' 1. 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")

		' 2. 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")

		' 3. 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
$vbLabelText   $csharpLabel

開始使用 IronPDF

立即在您的專案中使用IronPDF,並享受免費試用。

第一步:
green arrow pointer


安裝 IronPDF 庫

使用 NuGet 套件管理器安裝

要使用 NuGet 包管理器將 IronPDF 集成到您的 Hangfire .NET 項目中,請按照以下步驟進行:

  1. 在 Visual Studio 中打開解決方案資源管理器,右鍵點擊您的專案。

  2. 從內容選單中選擇「管理 NuGet 套件...」。

  3. 前往「瀏覽」標籤並搜尋 IronPDF。

  4. 從搜索結果中選擇IronPDF庫,然後點擊安裝按鈕。

  5. 接受任何許可協議提示。

    如果您想通過套件管理器主控台將 IronPDF 包含在您的專案中,請在套件管理器主控台中執行以下命令:

Install-Package IronPdf

這將會將 IronPDF 取回並安裝到您的專案中。

使用 NuGet 網站安裝

如需詳細了解 IronPDF,包括其功能、兼容性和其他下載選項,請訪問 NuGet 網站上的 IronPDF 頁面:https://www.nuget.org/packages/IronPdf

通過 DLL 安裝

或者,您可以直接將IronPDF納入您的專案,使用其dll檔案。從這個IronPDF 直接下載下載包含DLL的ZIP檔案。 解壓縮後,將 DLL 包含在您的專案中。

現在,讓我們修改應用程式以新增一個背景處理作業,將 HTTP 請求流程中的網站下載為 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
$vbLabelText   $csharpLabel

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
$vbLabelText   $csharpLabel

在這裡,我們創建了兩個 API,一個用於啟動背景工作來獲取網站 URL 並開始下載。 另一個 API 用於下載 PDF 結果。 API 如下所示。

Hangfire .NET Core(開發人員如何運作):圖7 - PDFGenerator APIs

結果如下所示。

Hangfire .NET Core(開發者運作方式):圖 8 - 輸出

授權(免費試用可用)

若要使上述程式碼在沒有浮水印的情況下運作,需要授權金鑰。 開發者在註冊IronPDF 免費試用後可以獲得試用許可。 試用許可證不需要信用卡。 您可以提供您的電子郵件地址並註冊免費試用。

結論

Hangfire 和 IronPDF 一起是一個很好的組合,可以在背景生成和下載 PDF。 我們可以在各種編程範式中使用 Hangfire 處理長時間運行的任務。 IronPDF 提供了一個靈活且易於使用的解決方案來生成 PDF。 要了解更多關於IronPDF的資訊,您可以查閱文件IronPDF文件

此外,您還可以探索Iron Software產品套件中的其他工具,這將有助於提高您的編程技能並實現現代應用程序需求。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# 空合併運算子(開發者如何使用)
下一個 >
C# 隊列(開發人員如何工作)