1
0

Getting Started

Storage

Hangfire 會將所有相關資訊會被序列化後保存到儲存區,如類型、方法或參數等。

儲存模型官方預設有以下幾種

Sql Server 2008+ Redis 2.6.12+ In-Memory Price
Open free
Startup $500 / per year
Business $1,500 / per year
Enterprise $4,500 / per year

資料來源日期: 2024/03/12

// Hangfire 1.8
GlobalConfiguration
    .Configuration
    .SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
    .UseSimpleAssemblyNameTypeSerializer()
    .UseRecommendedSerializerSettings()
    .UseSqlServerStorage("Database=Hangfire.Sample; Integrated Security=True;");

// Hangfire 1.7
GlobalConfiguration
    .Configuration
    .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
    .UseSimpleAssemblyNameTypeSerializer()
    .UseRecommendedSerializerSettings()
    .UseSqlServerStorage("Database=Hangfire.Sample; Integrated Security=True;", new SqlServerStorageOptions
    {
        CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
        SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
        QueuePollInterval = TimeSpan.Zero,
        UseRecommendedIsolationLevel = true,
        DisableGlobalLocks = true, // Migration to Schema 7 is required
    });

// Hangfire SQLite
GlobalConfiguration
    .Configuration
    .UseSQLiteStorage("HangfireExample.db"));

Server

啟動 Hangfire 伺服器

services.AddHangfireServer();

Using Dashboard UI

開啟 Dashboard 功能

app.UseHangfireDashboard();
  • Configuring Authorization

設定自定義驗證

app.UseHangfireDashboard("hangfire", new DashboardOptions
{
    Authorization = [new DashboardAuthorizationFilter()],
});
  • Read-only view

設定 UI 為 ReadOnly

app.UseHangfireDashboard("hangfire", new DashboardOptions
{
    IsReadOnlyFunc = (DashboardContext context) => true,
});
  • Change URL Mapping

修改 Dashboard UI 的預設根路由

app.UseHangfireDashboard("hangfire");
  • Change Back to site Link

修改返回按鈕的路由

app.UseHangfireDashboard("hangfire", new DashboardOptions
{
    AppPath = "/swagger", // 導向到 Swagger UI
});

BackToSite

  • Multiple Dashboards

設定不同資料來源的 Dashboard

app.UseHangfireDashboard(configuration.GetValue<string>("DashboardRoot"), new DashboardOptions
{
    Authorization = [new DashboardAuthorizationFilter()],
    // 指定 Dashboard 指定讀取,不能操作,如重新執行、再次加入排程與刪除任務等
    IsReadOnlyFunc = (DashboardContext context) => true,
    // 指定 Back to site 的連結
    AppPath = "/swagger",
}, new SQLiteStorage("HangfireExample2.db"));

Background Methods

排程可以直接執行特定方法Hangfire 會將方法(可使用非同步)、類型與參數序列化後保存到資料庫Hangfire 依照排程類型,分為以下四種

  • Fire-and-Forget jobs: 將任務丟入執行佇列,直接執行
BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-Forget"));
  • Delayed jobs: 延遲指定時間後,將任務丟入執行佇列
BackgroundJob.Schedule(() => Console.WriteLine("Delayed"), TimeSpan.FromDays(1));
  • Recurring jobs: 依照指定間隔,將任務丟入執行佇列

Cron Expression 測試

月中的日 週中的日 說明
0/30 * * * * * 每30秒執行一次
30 9 * * * * 每日早上09:30執行一次(UTC)
30 9 * * MON-FRI * 每週一到週五早上09:30執行一次(UTC)
30 09 * 1 * * 每月1號早上09:30執行一次(UTC)
0/30 0-30 9 * * * 每日早上09:00~09:30每30秒執行一次(UTC)
0/30 * 9-12 * * * 每日早上09:00~12:00每30秒執行一次(UTC)
0/30 * 9-12 1-5 * * 每月1號到5號早上09:00~12:00每30秒執行一次(UTC)
RecurringJob.AddOrUpdate("job_id", () => Console.Write("Recurring By CRON"), Cron.Daily);

RecurringJob.AddOrUpdate("job_id", () => Console.Write("Recurring By CRON expressions"), "* 0/1 * * ? *");

移除已存在的排程任務

RecurringJob.RemoveIfExists("job_id");

手動觸發已存在的排程任務

RecurringJob.Trigger("job_id");
  • Continuations: 指定的任務完成後,才丟入執行佇列
var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-Forget"));

BackgroundJob.ContinueJobWith(jobid, () => Console.WriteLine("Continuations"));
Description
An easy way to perform background processing in .NET and .NET Core application.
Readme 225 KiB
Languages
C# 100%