ASP.NET Core Hangfire 排程管理
Hangfire 是一款個人認為相當不錯的非同部步服務器,它脫離 Windows 工作排程,在 Web 檢視、重送任務,在 Hangfire 操作 UI 介面可以知道你指派給它的任務狀態,何時成功?為什麼失敗?(例外捕捉)下一次任務觸發時間?訊息可說是相當的完整。不過有點可惜的是,預設 Hangfire 操作介面沒有手動觸發任務的介面,幸好 Hangfire.Dashboard.Management 彌補了這個不足...
延伸閱讀
[Hangfire] 使用 Hangfire OWIN 建立非同步任務
開發環境
ASP.NET Core 3.1
VS 2019
範例內包含了 .NET Framework 4.8 的專案
實作
開一個 ASP.NET Core Web Application 專案 → 空白樣板
安裝套件
Install-Package Hangfire
Install-Package Hangfire.MemoryStorage
Install-Package Hangfire.Console
Install-Package Hangfire.Dashboard.Management配置 Configure
app.UseHangfireServer():設定 Queue、服務逾時、WorkCount 等等...
app.UseHangfireDashboard:設定權限、URL 等等..
配置 ConfigureServices
接著在這裡設定 Hangfire 要有那些功能,
config.UseDashboardMetric():小報表,可根據需求決定,Hangfire angfire 內建許多的報表
config.UseConsole() :來自 Hangfire.Console,輸出 Console.Log 到onsole.Log 到 Hangfire 頁面。
config.UseSqlServerStorage() :來自 Hangfire.SqlServer,排程資料放在 SQL Server。
config.UseManagementPages() :來自 Hangfire.Dashboard.Management,本篇主要的重點,任務管理工具,可以在 /hangfire 操作介面直接新增任務
GetModuleType 取出 Assembly 裡面所有的 ManagementPage 的物件
效果如下,DemoJob 是我這次演練的物件
ManagementPage
config.UseManagementPages 裡面放 ManagementPage 物件,設計要點如下,
在類別加上 Hangfire.Dashboard.Management.Metadata.ManagementPageAttribute。
方法加上 Hangfire.Dashboard.Management.Support.JobAttribute、System.ComponentModel.DisplayNameAttribute,這樣可以輕易地完成一個管理介面。
PerformContext 來自 Hangfire.Console,會在 Hangfire Hangfire 介面的 Log 主控台呈現。
IJobCancellationToken,當任務在執行過程當成被刪除,IsCancellationRequested = true
執行結果如下:
Task type Queue execution
原本要自己寫扣決定非同步類型,可以不需要寫了,交由給這個管理介面幫忙建立任務類型
Queue execution => BackgroundJob.Enqueue();
Timely execution => BackgroundJob.Schedule();
Delayed execution => BackgroundJob.ContinueWith();
Repeated execution => RecurringJob.AddOrUpdate();
PerformContext 呈現效果如下:
DisplayData
自訂輸入參數介面,只要在參數加上 DisplayDataAttribute,就能根據型別長出對應的 UI 介面,enum 對應下拉選單,還能自訂下拉選單的內容,例如 EncodingsInputDataList class
執行結果下圖:
完整設定如下
EncodingsInputDataList.GetData 回傳 Dictionary<string, string> 型別,就可以在任務管理介面看到下拉選單
任務執行配置
可以替任務方法加上 Hangfire 執行這些任務的設定,比如重試次數(AutomaticRetryAttribute)、停用並行(DisableConcurrentExecutionAttribute),詳情參考 https://docs.hangfire.io/en/latest/background-processing/throttling.html
CRON Expression
RecurringJob 排程工作可以根據 CRON 依照年、月、週、日來定義比較複雜的定期排程,Hangfire.Dashboard.Management 的 Repeated execution 則整合 https://github.com/bradymholt/cron-expression-descriptor
Cron Expression Analysis
紅框處,彼此互相 analysis
Cron Expression Builder
說明頁面描述可以支援到秒的單位,但是 Analysis 沒有支援到秒
Verified address
除了用 CRON Expression 幫我們產生語法之外,還能驗證這個語法是不是我們期望的,他的位置為 /hangfire/cron?cron=++++* ,不同的時間單位用 + 號隔開
每分鐘
每兩分鐘
參考來源
https://github.com/mccj/Hangfire.Dashboard.Management/tree/master/Samples
範例位置
https://github.com/yaochangyu/sample.dotblog/tree/master/Hangfire/Lab.HangfireManager
Last updated










