2022-09-05|閱讀時間 ‧ 約 6 分鐘

玩轉C#之【Hangfire】

介紹

類似Windows排程的一個套件,不過他有Dashboard可以看 可以用在商業用途

使用情境
簡單來說如果你需要定時的執行某一段程式就可以使用這個套件來幫你完成。

優點
  • Simple 開發簡易、安裝簡單、方便部署
  • Persistent 工作任務可存放於多種儲存裝置
  • Transparent 提供 Dashboard 可及時查看工作任務狀態
  • Reliable 執行失敗的工作任務有自動重試機制
  • Distributed 可分散部署多台以同時處理大量工作
  • 個別 Server 可設置同時處理數量以支援處理密集的工作任務

任務執行方式
  • Fire-and-forgot jobs: 站台啟動後自動執行一次
  • Delayed jobs: 可設定時間區間,每間格時間區間執行一次
  • Recurring jobs: 可設定Cron敘述,並重複執行多次
  • Continuations: 在某個job執行完後接續執行

版本
版本價格OpenFreeStartup500 / yearBusiness1,500 / yeaEnterprise4,500/ year

安裝方式

安裝環境NET6 主要安裝兩個套件
  • Hangfire
  • Hangfire.MemoryStorage
目前範例是將hangfire的紀錄存在記憶體之中
先註冊AddHangfire及AddHangfireServer,並且在MideeleWave的地方加入UseHangfireDashboard
Backgroud job方法
  • Fire-and-forgot jobs: 站台啟動後自動執行一次
// GET: api/<HangfireDemoController>
       [HttpGet]
       public IActionResult OneNigh()
       {
           // 第一招射後不理
           // fire and got:站台啟動後只會執行一次
           BackgroundJob.Enqueue(() => Debug.WriteLine("fire and got"));
           return Ok("射後不理");
       }
  • Delayed jobs: 可設定時間區間,每間格時間區間執行一次
[HttpGet]
       public IActionResult DelaySchedule()
       {
           Debug.WriteLine($"API現在時間:{DateTime.Now}");

           BackgroundJob.Schedule(
               () => Debug.WriteLine($"由HangFire排程發送,時間:{DateTime.Now}"),
               TimeSpan.FromSeconds(3));

           return Ok();
       }
  • Recurring jobs: 可設定Cron敘述,並重複執行多次
[HttpGet]
       public IActionResult TimedRepeat()
       {
           Debug.WriteLine($"API現在時間:{DateTime.Now}");
           //【 秒 分 時 日 月 周 年 】,其中年是可選型別,也就是說他如果在不設定年分的情況下是每年。
           RecurringJob.AddOrUpdate(
                () => Debug.WriteLine($"API現在時間:{DateTime.Now}")
                , "15 7 * * *");

           return Ok();

       }
  • Continuations: 在某個job執行完後接續執行
先取得jobId再使用ContinueJobWith,來撰寫前一分任務執行完後要做的事情。
// GET: api/<HangfireDemoController>
       [HttpGet]
       public IActionResult Continuations()
       {
           // 第一招射後不理
           // fire and got:站台啟動後只會執行一次
           var jobid = BackgroundJob.Enqueue(() => Debug.WriteLine("fire and got"));
          
           BackgroundJob.ContinueJobWith(jobid,()=> Debug.WriteLine("two and got"));

           return Ok("接續射後不理");
       }
關於各類型架構、Dashboard權限設定、工作全重設定…等等之後會專門寫一篇文章跟大家講解

參考資料

Hangfire 官方網站 過去整理的Hangfire文章 本篇已同步發表至個人部落格 https://moushih.com/2022ithome05/
鐵人賽文章
https://ithelp.ithome.com.tw/articles/10287721
分享至
成為作者繼續創作的動力吧!
程式語言、理財自我投資、加密貨幣、資訊安全 https://moushih.com/
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

發表回應

成為會員 後即可發表留言