在生产环境中测试,无水印。
随时随地满足您的需求。
获得30天的全功能产品。
几分钟内就能启动并运行。
在您的产品试用期间,全面访问我们的支持工程团队。
现代应用程序开发经常需要处理后台任务来处理庞大的任务,在这种情况下,我们需要后台作业处理程序来执行多个作业。 有很多作业处理程序,其中一种用于 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
为了了解 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。
在这里,我们可以看到返回日期、摘要和温度的天气 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 服务中托管仪表板。
当您在视图中启用仪表板时,仪表板位于/hangfire/扩展。 在该仪表板中,用户可以管理后台运行作业、安排后台作业、查看 "触发和遗忘作业 "以及重复作业。 可以使用职位 ID 识别这些职位。
成功的职位可在下面查看。
现在,当您的应用程序运行时,Hangfire 会根据配置的设置处理后台作业。
请记得查看Hangfire文档以获取更多高级配置选项和功能:Hangfire 文档,完整代码可以在GitHub Hangfire演示找到。
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
立即在您的项目中开始使用IronPDF,并享受免费试用。
要使用 NuGet 包管理器将 IronPDF 集成到 Hangfire .NET 项目中,请按照以下步骤操作:
打开 Visual Studio,在解决方案资源管理器中右键单击您的项目。
从上下文菜单中选择 "管理 NuGet 软件包..."。
转到浏览选项卡并搜索 IronPDF。
从搜索结果中选择 IronPdf 库,然后点击安装按钮。
接受任何许可协议提示。
如果您想通过软件包管理器控制台在项目中包含 IronPdf,那么请在软件包管理器控制台中执行以下命令:
Install-Package IronPdf
它会获取 IronPDF 并将其安装到你的项目中。
有关 IronPDF 的详细概述,包括其功能、兼容性和其他下载选项,请访问 NuGet 网站上的 IronPDF 页面 https://www.nuget.org/packages/IronPdf。
或者,您可以通过 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
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 产品套件的其他工具,这些工具将帮助您提高编程技能并满足现代应用程序的需求。