.NET 幫助

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

發佈 2024年1月14日
分享:

現代應用程式開發通常需要處理背景任務來處理大量工作,在此情況下,我們需要背景作業處理器來執行多個作業。 有許多作業處理程序,其中一種用於 C# .NET Core 應用程式的背景父作業處理程序是 Hangfire。在這篇博客中,我們將學習 Hangfire 背景作業以及如何將其與其他套件一起使用。IronPDF在背景中生成 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(開發者如何使用):圖1 - Swagger

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

Hangfire .NET Core(開發者運作方式):圖 2 - Weather 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
VB   C#

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)
VB   C#

建立背景作業

定義您想要作為背景作業運行的方法。 這些方法應該是具有無參數構造函數的類的靜態方法或實例方法。 這些工作可以作為定期工作來執行,也可以執行多個工作。

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
VB   C#

加入工作隊列

使用 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)
VB   C#

Hangfire 儀表板和服務器

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

// Run Hangfire server
app.UseHangfireServer();
app.UseHangfireDashboard();
// Run Hangfire server
app.UseHangfireServer();
app.UseHangfireDashboard();
' Run Hangfire server
app.UseHangfireServer()
app.UseHangfireDashboard()
VB   C#

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

services.AddHangfireServer();
services.AddHangfireServer();
services.AddHangfireServer()
VB   C#

即時執行任務

//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
VB   C#

定期作業

//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)
VB   C#

延遲作業

//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))
VB   C#

延續

//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!"))
VB   C#

批次作業

//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)
VB   C#

批次延續工作

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)
VB   C#

儀表板

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.

介紹 IronPDF

IronPDF是一个NuGet包來自Iron Software幫助讀取和生成 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
VB   C#

安裝 IronPDF 函式庫

C# NuGet 程式庫用于 PDF

安裝與 NuGet

Install-Package IronPdf
Java PDF JAR

下載 DLL

下載DLL

手動安裝到您的項目中

C# NuGet 程式庫用于 PDF

安裝與 NuGet

Install-Package IronPdf
Java PDF JAR

下載 DLL

下載DLL

手動安裝到您的項目中

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

第一步:
green arrow pointer

查看 IronPDFNuget 快速安裝和部署。已被下載超過800萬次,它正用C#改變PDF。

C# NuGet 程式庫用于 PDF nuget.org/packages/IronPdf/
Install-Package IronPdf

請考慮安裝 IronPDF DLL 直接下載並手動安裝到您的專案或GAC表單: IronPdf.zip

手動安裝到您的項目中

下載DLL

使用 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 文件納入您的項目。從這個地方下載包含 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
VB   C#

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
VB   C#

在這裡,我們創建了兩個 API,一個用於啟動後台任務以獲取網站 URL 並開始下載。 另一個 API 是下載 PDF 結果。 API 看起來如下所示。

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

結果如下所示。

Hangfire .NET Core(對開發人員的運作方式):圖8 - 輸出

授權(提供免費試用)

要使上述代碼無浮水印地運作,需要許可證金鑰。 開發人員在註冊後可獲取試用許可證。這裡而且,是的,試用許可證不需要信用卡。 您可以提供電子郵件地址並註冊免費試用。

結論

Hangfire和IronPDF是一個生成和下載PDF的絕佳組合,可以在背景中運行。 我們可以在各種程式設計範式中使用 Hangfire 來處理長時間運行的任務。 IronPDF 提供彈性且易於使用的解決方案來生成 PDF。 若要了解更多關於 IronPDF 的資訊,您可以查閱文件。這裡.

此外,您還可以探索其他工具來自Iron Software這將幫助您提高編程技能並實現現代應用需求。

< 上一頁
C# 空合併運算子(開發者如何使用)
下一個 >
C# 隊列(開發人員如何工作)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >