在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
現代應用程式開發經常需要處理背景任務以處理龐大的任務,在這種情境下,我們需要背景任務處理器來執行多個工作。 有許多作業處理器,其中一個用於 C# .NET Core 應用程式的背景母作業處理器是 Hangfire。在這篇博客中,我們將學習 Hangfire 背景作業,以及如何將其與其他套件一起使用。IronPDF 用於生成 PDF生成 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)
可以在 Configure 方法中添加 Hangfire 儀表板和伺服器。
// Run Hangfire server
app.UseHangfireServer();
app.UseHangfireDashboard();
// Run Hangfire server
app.UseHangfireServer();
app.UseHangfireDashboard();
' Run Hangfire server
app.UseHangfireServer()
app.UseHangfireDashboard()
伺服器也可以在 ConfigureServices 中添加。
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 生成是一个NuGet從 套件Iron Software 的 PDF 庫用於閱讀和生成 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 集成到您的項目中。從此處下載包含 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 免費試用. 試用許可證不需要信用卡。 您可以提供您的電子郵件地址並註冊免費試用。
Hangfire 和 IronPDF 一起是一個很好的組合,可以在背景生成和下載 PDF。 我們可以在各種編程範式中使用 Hangfire 處理長時間運行的任務。 IronPDF 提供了一個靈活且易於使用的解決方案來生成 PDF。 若要了解有關 IronPDF 的更多資訊,您可以查看文件。IronPDF 文件檔案.
此外,您還可以探索其他工具Iron Software產品套件這將幫助您提高編碼技能,並達到現代應用程式的需求。