푸터 콘텐츠로 바로가기
.NET 도움말

Hangfire .NET Core (How It Works For Developers)

Modern application development often requires processing background tasks to handle huge workloads. In such scenarios, we need background job handlers capable of executing multiple jobs. One such background job handler for C# .NET Core applications is Hangfire. In this blog, we are going to learn about managing Hangfire background jobs and how to use them with other packages like IronPDF for PDF Generation to generate PDF documents in the background.

Hangfire simplifies the implementation of background processing in ASP.NET Core or .NET Core 6 Web API applications by providing a reliable and flexible framework for managing and executing background jobs. Hangfire is available as a NuGet package and can be installed using the .NET CLI as shown below:

dotnet add package Hangfire --version 1.8.6

Implementation in .NET Core Web API

To learn about Hangfire, let's create a simple .NET Core API application and install Hangfire using the CLI.

dotnet new webapi -n HangfireDemo
cd HangfireDemo
dotnet build
dotnet add package Hangfire --version 1.8.6
dotnet build
dotnet new webapi -n HangfireDemo
cd HangfireDemo
dotnet build
dotnet add package Hangfire --version 1.8.6
dotnet build
SHELL

Here we are creating a simple weather REST API using .NET CLI. The first line creates a .NET Core Web API project named HangfireDemo to execute API endpoints. The second line navigates to our newly created folder "HangfireDemo," and then we build the project. Next, we add the Hangfire NuGet package to our project and build it again. After this, you can open your project in any editor of your choice, such as Visual Studio 2022 or JetBrains Rider. Now if you run the project you can see the Swagger as follows:

Hangfire .NET Core (How It Works For Developer): Figure 1 - Swagger

Here we can see the weather GET APIs, which return date, summary, and temperature.

Hangfire .NET Core (How It Works For Developer): Figure 2 - Weather GET API

Now let us add a Hangfire background job processor. Open the project in Visual Studio.

Add Hangfire Job Processor

Configure Hangfire in your application, typically in the Startup.cs file. This involves setting up a job storage and initializing the Hangfire server.

// Startup.cs
using Hangfire;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Hangfire services and use SQL Server as storage option
        services.AddHangfire(config => config.UseSqlServerStorage("your_connection_string"));
        services.AddHangfireServer();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // Use Hangfire Server and Dashboard for monitoring and managing jobs
        app.UseHangfireServer();
        app.UseHangfireDashboard();
        // Your other configuration settings
    }
}
// Startup.cs
using Hangfire;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add Hangfire services and use SQL Server as storage option
        services.AddHangfire(config => config.UseSqlServerStorage("your_connection_string"));
        services.AddHangfireServer();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // Use Hangfire Server and Dashboard for monitoring and managing jobs
        app.UseHangfireServer();
        app.UseHangfireDashboard();
        // Your other configuration settings
    }
}
$vbLabelText   $csharpLabel

The ConfigureServices method is used to add storage to save Hangfire's newly created jobs. Here, a SQL Server database is used. The SQL Server connection string should be replaced with "your_connection_string". One can also use in-memory storage with Hangfire.InMemory.

dotnet add package Hangfire.InMemory --version 0.6.0

And replace with:

services.AddHangfire(configuration => { configuration.UseInMemoryStorage(); });
services.AddHangfire(configuration => { configuration.UseInMemoryStorage(); });
$vbLabelText   $csharpLabel

Create Background Jobs

Define the methods you want to run as background jobs. These methods should be static or instance methods of a class with a parameterless constructor. Jobs can be run as recurring jobs, or you can run multiple jobs simultaneously.

public class MyBackgroundJob
{
    public void ProcessJob()
    {
        // Background job logic, can be a recurring job or multiple jobs
        Console.WriteLine("Background job is running...");
    }
}
public class MyBackgroundJob
{
    public void ProcessJob()
    {
        // Background job logic, can be a recurring job or multiple jobs
        Console.WriteLine("Background job is running...");
    }
}
$vbLabelText   $csharpLabel

Enqueue Jobs

Enqueue background jobs using the Hangfire API. You can schedule background jobs to run at a specific time, after a delay, or regularly.

// Enqueue a job to run immediately
BackgroundJob.Enqueue<MyBackgroundJob>(x => x.ProcessJob());

// Schedule a job to run after a 5-minute delay
BackgroundJob.Schedule<MyBackgroundJob>(x => x.ProcessJob(), TimeSpan.FromMinutes(5));

// Schedule a recurring job using a job ID
RecurringJob.AddOrUpdate<MyBackgroundJob>("jobId", x => x.ProcessJob(), Cron.Daily);
// Enqueue a job to run immediately
BackgroundJob.Enqueue<MyBackgroundJob>(x => x.ProcessJob());

// Schedule a job to run after a 5-minute delay
BackgroundJob.Schedule<MyBackgroundJob>(x => x.ProcessJob(), TimeSpan.FromMinutes(5));

// Schedule a recurring job using a job ID
RecurringJob.AddOrUpdate<MyBackgroundJob>("jobId", x => x.ProcessJob(), Cron.Daily);
$vbLabelText   $csharpLabel

Hangfire Dashboard and Server

The Hangfire dashboard and server can be added in the Configure method for real-time job monitoring.

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

The server can also be added in ConfigureServices.

services.AddHangfireServer();
services.AddHangfireServer();
$vbLabelText   $csharpLabel

Fire and Forget Jobs

// Fire and forget jobs are executed only once and almost immediately after creation.
var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget!")); // Job ID for 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!")); // Job ID for fire and forget job
$vbLabelText   $csharpLabel

Recurring Jobs

// Recurring jobs fire many times based on a specified CRON schedule.
RecurringJob.AddOrUpdate("myrecurringjob", () => Console.WriteLine("Recurring!"), Cron.Daily);
// Recurring jobs fire many times based on a specified CRON schedule.
RecurringJob.AddOrUpdate("myrecurringjob", () => Console.WriteLine("Recurring!"), Cron.Daily);
$vbLabelText   $csharpLabel

Delayed Jobs

// Delayed jobs are executed only once but after a specified interval.
var jobId = BackgroundJob.Schedule(() => Console.WriteLine("Delayed!"), TimeSpan.FromDays(7));
// Delayed jobs are executed only once but after a specified interval.
var jobId = BackgroundJob.Schedule(() => Console.WriteLine("Delayed!"), TimeSpan.FromDays(7));
$vbLabelText   $csharpLabel

Continuations

// Continuation jobs are executed once their parent jobs have completed.
BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine("Continuation!"));
// Continuation jobs are executed once their parent jobs have completed.
BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine("Continuation!"));
$vbLabelText   $csharpLabel

Batch Job

// Batch is a group of background jobs created atomically and considered as a single entity.
var batchId = BatchJob.StartNew(x =>
{
    x.Enqueue(() => Console.WriteLine("Job 1"));
    x.Enqueue(() => Console.WriteLine("Job 2"));
});
// Batch is a group of background jobs created atomically and considered as a single entity.
var batchId = BatchJob.StartNew(x =>
{
    x.Enqueue(() => Console.WriteLine("Job 1"));
    x.Enqueue(() => Console.WriteLine("Job 2"));
});
$vbLabelText   $csharpLabel

Batch Continuation 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"));
});
// Batch continuation is fired when all background jobs in a parent batch are finished.
BatchJob.ContinueBatchWith(batchId, x =>
{
    x.Enqueue(() => Console.WriteLine("Last Job"));
});
$vbLabelText   $csharpLabel

Dashboard

Hangfire Dashboard is where you can find all information about your background jobs. It is written as an OWIN middleware (if you are not familiar with OWIN, don’t worry), so you can plug it into your ASP.NET, ASP.NET MVC, Nancy, and ServiceStack applications, as well as use the OWIN Self-Host feature to host Dashboard inside Console Applications or Windows Services.

When you have the dashboard enabled, it is available at the /hangfire/ extension. In this dashboard, you can manage background running jobs, schedule background jobs, and view fire and forget jobs along with recurring jobs. The jobs can be identified using a job ID.

Live processing

Hangfire .NET Core (How It Works For Developer): Figure 3 - Live Processing of Jobs

Succeeded Jobs

View successful jobs below.

Hangfire .NET Core (How It Works For Developer): Figure 4 - Succeeded Jobs

Scheduled jobs

Hangfire .NET Core (How It Works For Developer): Figure 5 - Scheduled Jobs

When your application runs, Hangfire will take care of processing the background jobs based on the configured settings.

Remember to check the Hangfire documentation for more advanced configuration options and features: Hangfire Documentation and complete code can be found on GitHub Hangfire Demo.

Introducing IronPDF

IronPDF for .NET PDF Generation is a NuGet package from Iron Software's PDF Library that helps to read and generate PDF docs. It can convert easily formatted documents with style information to PDF. IronPDF can easily generate PDFs from HTML content. It can download the HTML from the URL and then generate PDFs.

The main attraction of IronPDF is its HTML to PDF Conversion function, which preserves layouts and styles. It can create PDFs from web content, ideal for reports, invoices, and documentation. This feature supports converting HTML files, URLs, and HTML strings to PDFs.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 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");

        // 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");

        // 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();

        // 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");

        // 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");

        // Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
$vbLabelText   $csharpLabel

Get started with IronPDF

Install IronPDF Library

Install Using NuGet Package Manager

To integrate IronPDF into your Hangfire .NET project using the NuGet Package Manager, follow these steps:

  1. Open Visual Studio and in the Solution Explorer, right-click on your project.
  2. Choose “Manage NuGet Packages…” from the context menu.
  3. Go to the Browse tab and search for IronPDF.
  4. Select the IronPDF library from the search results and click the Install button.
  5. Accept any license agreement prompt.

If you prefer using the Package Manager Console, execute the following command:

Install-Package IronPdf

This will fetch and install IronPDF into your project.

Install Using NuGet Website

For a detailed overview of IronPDF, including features, compatibility, and additional download options, visit the IronPDF page on the NuGet website at https://www.nuget.org/packages/IronPdf.

Install Via DLL

Alternatively, you can incorporate IronPDF directly into your project using its DLL file. Download the ZIP file containing the DLL from this IronPDF Direct Download. Unzip it, and include the DLL in your project.

Now let's modify our application to add a background processing job to download a website as a PDF file.

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);
    }
}
$vbLabelText   $csharpLabel

IronPDF has an inbuilt method to download a website from a URL and save it as a PDF document. We are going to use this method in our job to download and save it to a specified location. This background job can be modified to take multiple website URLs and save them as PDFs.

Now, let's add a controller to expose the PDF generation and download APIs.

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" };
    }
}
$vbLabelText   $csharpLabel

Here we have created two APIs: one to start the background job and take the website URL for initiating the download, and another API to download the resulting PDF. The APIs are depicted as shown below.

Hangfire .NET Core (How It Works For Developer): Figure 7 - PDFGenerator APIs

And the result looks like this:

Hangfire .NET Core (How It Works For Developer): Figure 8 - Output

Licensing (Free Trial Available)

For the above code to work without watermarks, a license key is required. A trial license is available for developers upon registering with IronPDF Free Trial. No credit card is required for a trial license. You can provide your email ID and register for a free trial.

Conclusion

Hangfire and IronPDF together are a great combination for generating and downloading PDFs in the background. Hangfire enables efficient processing of long-running tasks, while IronPDF provides a flexible and easy-to-use solution for PDF generation. To learn more about IronPDF, you can visit the IronPDF Documentation.

Also, explore other tools from the Iron Software Product Suite which can enhance your coding skills and meet modern application requirements.

자주 묻는 질문

.NET Core에서 행파이어란 무엇인가요?

행파이어는 ASP.NET Core 또는 .NET Core 6 애플리케이션에서 백그라운드 처리 구현을 간소화하는 프레임워크입니다. 백그라운드 작업 관리 및 실행을 위한 안정적이고 유연한 솔루션을 제공합니다.

.NET Core 애플리케이션에 Hangfire를 설치하려면 어떻게 해야 하나요?

행파이어는 NuGet 패키지로 설치할 수 있습니다. 다음 명령으로 .NET CLI를 사용하여 추가할 수 있습니다: 닷넷 추가 패키지 Hangfire --버전 1.8.6.

행파이어가 지원하는 백그라운드 작업의 유형은 무엇인가요?

Hangfire는 실행 후 삭제 작업, 지연 작업, 반복 작업, 연속 작업 등 다양한 유형의 백그라운드 작업을 지원합니다.

.NET Core 애플리케이션에서 행파이어를 어떻게 구성하나요?

행파이어는 작업 저장소를 설정하고 행파이어 서버를 초기화하는 Startup.cs 파일에 구성됩니다. 여기에는 일반적으로 Hangfire 서비스를 추가하고 SQL Server 또는 인메모리 스토리지를 설정하는 작업이 포함됩니다.

행파이어 대시보드란 무엇인가요?

행파이어 대시보드는 백그라운드 작업을 모니터링하고 관리하기 위한 도구입니다. 실시간 처리, 성공한 작업, 예약된 작업에 대한 정보를 제공하며 웹 인터페이스를 통해 액세스할 수 있습니다.

행파이어를 사용하여 백그라운드 작업을 만들려면 어떻게 해야 하나요?

작업으로 실행할 메서드를 정의한 다음 Hangfire API를 사용하여 대기열에 추가하여 백그라운드 작업을 생성할 수 있습니다. 작업은 즉시, 지연 후 또는 반복적으로 실행되도록 예약할 수 있습니다.

.NET Core를 사용하여 백그라운드에서 PDF 생성 작업을 수행하려면 어떻게 해야 하나요?

HTML에서 PDF로의 변환을 지원하는 PDF 라이브러리를 사용하여 백그라운드에서 PDF 생성 작업을 수행할 수 있습니다. 이를 Hangfire와 같은 백그라운드 작업 처리 프레임워크에 통합하여 HTML 콘텐츠에서 PDF 생성을 자동화할 수 있습니다.

.NET에서 PDF 생성 라이브러리의 기능은 무엇인가요?

PDF 생성 라이브러리는 HTML 문자열, HTML 파일 및 URL을 PDF로 변환할 수 있습니다. 레이아웃과 스타일을 보존하며 웹 콘텐츠에서 보고서, 송장 및 문서를 생성하는 데 유용합니다.

.NET 프로젝트에 PDF 생성 라이브러리를 설치하려면 어떻게 해야 하나요?

PDF 생성 라이브러리는 Visual Studio의 NuGet 패키지 관리자를 사용하거나 패키지 관리자 콘솔에서 특정 명령을 사용하여 설치할 수 있습니다. 라이브러리 웹사이트에서 직접 DLL을 다운로드하여 설치할 수도 있습니다.

워터마크가 없는 PDF 생성 라이브러리를 사용하려면 무엇이 필요하나요?

워터마크가 없는 PDF 생성 라이브러리를 사용하려면 일반적으로 라이선스 키가 필요합니다. 라이브러리 웹사이트에서 등록하면 무료 평가판 라이선스를 사용할 수 있습니다.

PDF 생성 툴을 .NET Core의 Hangfire와 어떻게 통합할 수 있나요?

PDF 생성 라이브러리를 사용하여 HTML을 PDF로 변환하는 백그라운드 작업을 설정하여 PDF 생성 도구를 .NET Core의 Hangfire와 통합할 수 있습니다. 이를 통해 애플리케이션에서 문서를 자동으로 생성하고 관리할 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.