Thực thi các Background Tasks sử dụng Hangfire

Hangfire là một open source framework giúp chúng ta tạo, thực thi và quản lý các background jobs. Chẳng hạn,
Mass notifications/newsletter
Batch import from xml, csv, json
Creation of archives
Firing off web hooks
Deleting users
Building different graphs
Image/video processing
Purge temporary files
Recurring automated reports
Database maintenance




Hangfire hỗ trợ tất cả các loại background tasks (Short-running and long-running, CPU intensive and I/O intensive, One shot and recurrent)
Hangfire hỗ trợ đa dạng các loại Databases (MS SQL Server, Redis, PostgreSQL, MongoDB, C1 CMS, ...) giúp cho việc lưu các tasks này được dễ dàng hơn.
Hangfire cũng hỗ trợ Automatic Retries (Khi thực thi job của bạn mà có vấn đề gì xảy ra, Hangfire sẽ tự động thực thi lại sau một khoảng thời gian sau đó)
Có tích hợp giao diện Monitoring UI trên giao diện web giúp ta quản lý các job được dễ dàng hơn

Các bạn tải về và chạy thử ví dụ ở đây
Về cơ bản để cấu hình Hangfire với ASP .NET Core sẽ gồm các bước sau

Cài đặt các Nuget
// Hangfire core package
Hangfire.Core
// Tùy vào loại database bạn chọn, Ở đây sử dụng MS SQL Server
Hangfire.SqlServer
// Dành riêng cho các ứng dụng ASP .NET Core
Hangfire.AspNetCore

Khởi tạo database cho Hangfire

CREATE DATABASE [HangfireTest]
GO

Cấu hình ứng dụng ASP .NET Core để kết nối tới database vừa tạo ở trên.

https://docs.hangfire.io/en/latest/getting-started/aspnet-core-applications.html

Khởi chạy trang web

Mở trang Monitoring UI
http:///hangfire

Bạn có thể gửi job event từ bất kỳ client nào, Giả sử ở đây gửi từ Console App (Cài đặt Hangfire.Core, Hangfire.SqlServer từ Nuget)

string dbConnection = "Server=localhost;Database=HangfireTest;User=sa;Password=Pass@word;";
GlobalConfiguration.Configuration.UseSqlServerStorage(dbConnection);
BackgroundJob.Enqueue(() => Console.WriteLine("Hello!"));

Bạn cũng có thể gửi job event từ chính server ở trên bạn cấu hình cho Hangfire sử dụng các class như IBackgroundJobClient

public class HomeController : Controller
{
    private readonly IBackgroundJobClient _jobClient;

    public HomeController(IBackgroundJobClient jobClient)
    {
        _jobClient = jobClient;
    }
    public IActionResult Index()
    {
        _jobClient.Enqueue(() => Console.WriteLine("Hello world from Hangfire!"));
        return View();
    }
}

Xem kết quả các jobs
http:///hangfire/jobs/succeeded

Tham khảo thêm
https://www.hangfire.io
https://docs.hangfire.io/en/latest/

Một số thư viện có chức năng tương tự bạn có thể tham khảo
Coravel
FluentScheduler


Tiếp tục cập nhật ...