MinimalAPI Hangfire

Minimal API如何快速套用Hangfire

【Maxine】趙家瑜 (昕力 DTD) 2025/09/08 17:10:55
44

一、Hangfire

開源的,用於在特定事件和時間安排作業。

• Hangfire Dashboard 還可以讓我們輕鬆監控和管理所有事情。

二、如何安裝

2-1. 安裝 Hangfire NuGet 套件

2-2. Program.cs建立hangfire

// 加上第5,12行
(省略)

// Add Hangfire
builder.Services.AddHangfireServices(builder.Configuration);

var app = builder.Build();

(省略)

//HangFire Dashboard
app.UseHangfireDashboard("/hangfire");

 

2-3. Hangfire擴充方法

public static void AddHangfireServices(this IServiceCollection services, IConfiguration _configuration)
{
    // 連線字串
    string? conn = _configuration.GetSection("Database").Get<DatabaseConfigDetail[]>().Where(x => x.CompName.ToString() == "CDFH").First().ConnectionString;

    // Add Hangfire
    services.AddHangfire(x => {
        x.UseSqlServerStorage(conn, new SqlServerStorageOptions
        {
            CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
            SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
            QueuePollInterval = TimeSpan.Zero,
            UseRecommendedIsolationLevel = true,
            DisableGlobalLocks = true, // Migration to Schema 7 is required
        });
        
        // 管理頁面
        x.UseManagementPages(typeof(RecurringJobsService).Assembly);
    });

    // 加入 Hangfire Server
    services.AddHangfireServer(options =>
    {

    });
}

 

2-4. 排程列表 RecurringJobsService

/// <summary>
/// 排程註冊主檔
/// </summary>
[ManagementPage(MenuName = "RecurringJobManage", Title = nameof(RecurringJobsService))]

public class RecurringJobsService : IJob
{
    private readonly ILogger<RecurringJobsService> _logger;
     /// <summary>
     /// 初始化建構
     /// </summary>
     public RecurringJobsService(ILogger<RecurringJobsService> logger) 
     {
        _logger = logger;
        _fileProcessService = fileProcessService;
        _syncDataService = syncDataService;
     }
    
     [DisplayName("SyncDataJob")]
     //防止排程重複執行(等幾秒沒有執行則視為TimeOut)
     [DisableConcurrentExecution(60)]
     public async Task SyncDataJob(IJobCancellationToken? cancellationToken = null)
     {
         if (cancellationToken != null)
         {
             if (cancellationToken.ShutdownToken.IsCancellationRequested)
             {
                 return;
             }
         }
         
         // 呼叫排程服務
         // your function
     }
}

 

三、執行

3-1. hangfire dashborad

• 執行出現這畫面,表示成功了

 若預設首頁不同,請加上在url後加上/hangfire

 

3-2. 執行排程

* 點Management,出現所有排程列表

 

* 若要debug執行測試,Task type: Immediate(立即)

 

### 3-3. 設定排程

* 若要定期執行,依照圖上步驟設定執行週期,設定完成會在Recurring Jobs出現該排程

使用 [crontab](https://crontab.informaship.com/) 設定排程時間

 

### 3-4. 刪除排程

* 依照圖上步驟刪除

 

 

## 四、參考文件

 

* Hangfire Documentation

【Maxine】趙家瑜 (昕力 DTD)