.NET 帮助

Hangfire .NET Core (开发人员的使用方式)

发布 2024年一月14日
分享:

现代应用程序开发经常需要处理后台任务来处理庞大的任务,在这种情况下,我们需要后台作业处理程序来执行多个作业。作业处理程序有很多,Hangfire 就是这样一个适用于 C# .NET Core 应用程序的后台父作业处理程序。在本博客中,我们将了解 Hangfire 后台作业,以及如何将它与其他软件包一起使用,如 IronPDF 在后台生成 PDF 文档。

简介

Hangfire 通过为管理和执行后台作业提供可靠而灵活的框架,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 - 天气 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.SQL 服务器的内存存储。

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#

Enqueue Jobs

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

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

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

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 控制面板上,您可以找到有关后台作业的所有信息。它是作为 OWIN 中间件编写的 (如果您对 OWIN 不熟悉,不用担心)因此,您可以将其插入您的 ASP.NET、ASP.NET MVC、Nancy 和 ServiceStack 应用程序,并使用 OWIN 自助托管 功能,在控制台应用程序或 Windows 服务中托管 Dashboard。

在视图中启用控制面板后,控制面板将位于 /hangfire/ 扩展。在该仪表板中,可以管理后台运行的作业、安排后台作业、查看 "触发和遗忘 "作业以及重复作业。可以使用作业 ID 识别作业。

实时处理

Hangfire .NET Core(如何为开发人员工作):图 3 - 实时处理作业

成功的工作

成功的工作可在下面查看。

Hangfire .NET Core(如何为开发人员工作):图 4 - 成功的工作

计划工作

Hangfire .NET Core(如何为开发人员工作):图 5 - 计划任务

现在,当您的应用程序运行时,Hangfire 会根据配置的设置来处理后台作业。

记得查看 Hangfire 文档,了解更多高级配置选项和功能:Hangfire 文档 完整代码可在 GitHub.

介绍 IronPDF

IronPDF 是一个 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
VB   C#

安装 IronPDF 库

适用于PDF的C# NuGet库

安装使用 NuGet

Install-Package IronPdf
Java PDF JAR

下载 DLL

下载DLL

手动安装到你的项目中

适用于PDF的C# NuGet库

安装使用 NuGet

Install-Package IronPdf
Java PDF JAR

下载 DLL

下载DLL

手动安装到你的项目中

开始在您的项目中使用IronPDF,并立即获取免费试用。

第一步:
green arrow pointer

查看 IronPDFNuget 用于快速安装和部署。它有超过800万次下载,正在使用C#改变PDF。

适用于PDF的C# NuGet库 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 网站 https://www.nuget.org/packages/IronPdf 上的 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#

在这里,我们创建了两个应用程序接口,一个用于启动后台作业,获取网站 URL 并启动下载。另一个 API 用于下载 PDF 结果。API 如下所示。

Hangfire .NET Core(如何为开发人员工作):图 7 - PDFGenerator API

结果如下。

Hangfire .NET Core(如何为开发人员工作):图 8 - 输出

许可 (可免费试用)

要使上述代码在没有水印的情况下工作,需要许可证密钥。注册开发人员可获得试用许可证 这里 是的,试用许可证不需要信用卡。用户可以提供电子邮件 ID 并注册免费试用。

结论

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

此外,您还可以从 铁软件 它将帮助你提高编码技能,满足现代应用程序的要求。

< 前一页
C# 空合并运算符(开发人员如何使用)
下一步 >
C# 队列(开发人员如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >