在实际环境中测试
在生产中测试无水印。
随时随地为您服务。
现代应用程序开发经常需要处理后台任务来处理庞大的任务,在这种情况下,我们需要后台作业处理程序来执行多个作业。 作业处理程序有很多,Hangfire 就是这样一种用于 C# .NET Core 应用程序的后台父作业处理程序。在本博客中,我们将了解 Hangfire 后台作业以及如何将其与其他软件包(如用于生成 PDF 的 IronPDF在后台生成 PDF 文档。
Hangfire通过为管理和执行后台作业提供可靠而灵活的框架,《ASP.NET Core》简化了 ASP.NET Core 或 .NET Core 6 Web API 应用程序中后台处理的实施。 Hangfire 可作为NuGet软件包,并可使用 .NET CLI 安装,如下所示。
dotnet add package Hangfire --version 1.8.6
为了了解 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。
在这里,我们可以看到返回日期、摘要和温度的天气 GET API。
现在,让我们添加一个 Hangfire 后台作业处理器。 在 Visual Studio 中打开项目。
在应用程序中配置 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
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()
{
// 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
使用 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)
可以在配置方法中添加 Hangfire 仪表板和服务器。
// Run Hangfire server
app.UseHangfireServer();
app.UseHangfireDashboard();
// Run Hangfire server
app.UseHangfireServer();
app.UseHangfireDashboard();
' Run Hangfire server
app.UseHangfireServer()
app.UseHangfireDashboard()
服务器也可以在配置服务中添加。
services.AddHangfireServer();
services.AddHangfireServer();
services.AddHangfireServer()
//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
//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)
//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))
//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!"))
//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)
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)
您可以在 Hangfire Dashboard 上找到有关后台工作的所有信息。 它是作为 OWIN 中间件编写的(如果您对 OWIN 不熟悉,不用担心)因此,您可以将其插入您的 ASP.NET、ASP.NET MVC、Nancy 和 ServiceStack 应用程序,并使用OWIN 自助托管在控制台应用程序或 Windows 服务中托管 Dashboard 的功能。
当您在视图中启用仪表板时,仪表板位于 /hangfire/ 扩展名。 在该仪表板中,用户可以管理后台运行作业、安排后台作业、查看 "触发和遗忘作业 "以及重复作业。 可以使用职位 ID 识别这些职位。
成功的职位可在下面查看。
现在,当您的应用程序运行时,Hangfire 会根据配置的设置处理后台作业。
切记查看 Hangfire 文档,了解更多高级配置选项和功能:Hangfire文档完整代码可在GitHub Hangfire 演示.
IronPDF for .NET PDF 生成工具是一个NuGet从Iron Software 的 PDF 库帮助读取和生成PDF文档。 它可以将包含样式信息的格式化文档轻松转换为PDF。 IronPDF 可以轻松地从 HTML 内容生成 PDF。 它可以从 URL 下载 HTML,然后生成 PDF。
IronPDF 的主要吸引力在于其HTML 转换为 PDF翻译时,必须使用".NET "和 "Python "功能,以保留布局和样式。 它可以根据网页内容创建 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
立即在您的项目中开始使用IronPDF,并享受免费试用。
要使用 NuGet 包管理器将 IronPDF 集成到 Hangfire .NET 项目中,请按照以下步骤操作:
打开 Visual Studio,在解决方案资源管理器中右键单击您的项目。
从上下文菜单中选择 "管理 NuGet 软件包..."。
转到浏览选项卡并搜索 IronPDF。
从搜索结果中选择 IronPdf 库,然后点击安装按钮。
接受任何许可协议提示。
如果您想通过软件包管理器控制台在项目中包含 IronPdf,那么请在软件包管理器控制台中执行以下命令:
Install-Package IronPdf
它会获取 IronPDF 并将其安装到你的项目中。
有关 IronPDF 的详细概述,包括其功能、兼容性和其他下载选项,请访问 NuGet 网站上的 IronPDF 页面 https://www.nuget.org/packages/IronPdf。
另外,您也可以使用 IronPdf 的 dll 文件将其直接集成到您的项目中。从以下链接下载包含 DLL 的 ZIP 文件IronPDF 直接下载. 解压缩,并将 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
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 产品套件它将帮助你提高编码技能,满足现代应用程序的要求。