.NET 帮助

Hangfire .NET Core(它如何为开发人员工作)

Chipego
奇佩戈-卡琳达
2024年一月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的核心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 - 天气获取 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

Enqueue 工作

使用 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 控制面板和服务器

可以在配置方法中添加 Hangfire 仪表板和服务器。

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

服务器也可以在配置服务中添加。

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's 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();

        // 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 安装

或者,您可以通过 DLL 文件将 IronPDF 直接集成到您的项目中。可以从此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 免费试用的试用许可证。 试用许可证无需信用卡。 您可以提供您的电子邮件 ID 并注册免费试用。

结论

Hangfire 和 IronPDF 一起是在后台生成和下载 PDF 的绝佳组合。 我们可以在各种编程范式中使用 Hangfire 来处理长期运行的任务。 IronPDF 提供了灵活易用的 PDF 生成解决方案。 要了解有关IronPDF的更多信息,您可以查找文档IronPDF文档

此外,您可以探索来自Iron Software 产品套件的其他工具,这些工具将帮助您提高编程技能并满足现代应用程序的需求。

Chipego
软件工程师
Chipego 拥有出色的倾听技巧,这帮助他理解客户问题并提供智能解决方案。他在 2023 年加入 Iron Software 团队,此前他获得了信息技术学士学位。IronPDF 和 IronOCR 是 Chipego 主要专注的两个产品,但他对所有产品的了解每天都在增长,因为他不断找到支持客户的新方法。他喜欢 Iron Software 的合作氛围,公司各地的团队成员贡献他们丰富的经验,以提供有效的创新解决方案。当 Chipego 离开办公桌时,你经常可以发现他在看书或踢足球。
< 前一页
C# 空合并(开发人员如何使用)
下一步 >
C# 队列(开发人员如何使用)