天天看點

Hangfire實戰(一)------Hangfire+SQL Server實作簡單的任務排程

Hangfire實戰(一)------Hangfire+SQL Server實作簡單的任務排程

Hangfire:一個開源的任務排程架構

開發環境:VS2017,SQL Server 2012,.NET Framework 4.5

項目類型:控制台應用程式

1.在vs的程式包控制台中為項目添加Hangfire支援    

PM>Install-Package Hangfire

2.配置sql server連接配接

GlobalConfiguration.Configuration.UseColouredConsoleLogProvider().UseSqlServerStorage("Data Source=127.0.0.1;User ID=sa;Password=XXXX;Initial Catalog=Hangfire;Connection Reset=False;");

3.建立基本任務

任務類别 任務描述 基本文法
Fire-and-forget 将目前任務放入到一個持久化的隊列中,以便程式可以繼續執行 BackgroundJob.Enqueue
Delayed 任務在未來的一個時間點執行 BackgroundJob.Schedule
Recurring 可重複執行的任務 RecurringJob.AddOrUpdate
Continuations 将多個任務連接配接成類似工作流的形式順序執行 BackgroundJob.ContinueWith

4.建立任務代碼參考: 

using (var server = new BackgroundJobServer()) {

    //支援基于隊列的任務處理:任務執行不是同步的,而是放到一個持久化隊列中,以便馬上把請求控制權傳回給調用者

    BackgroundJob.Enqueue(() => Console.WriteLine("Simple111"));

    //延遲任務執行:不是馬上調用方法,而是設定一個未來時間點再來執行。   

    BackgroundJob.Schedule(() => Console.WriteLine("Reliable!"), TimeSpan.FromSeconds(5));

    //一行代碼添加重複執行的任務,其内置了常見的時間循環模式,也可基于CRON表達式來設定複雜的模式。

    RecurringJob.AddOrUpdate(() => Console.WriteLine("Transparent!"), Cron.Minutely);

    //Continuations: Continuations allow you to define complex workflows by chaining multiple background jobs together.

    var jobId = BackgroundJob.Enqueue(() => Test("========First job"));

    BackgroundJob.ContinueWith(jobId, () => Test("========Start execute next task"));          

    Console.WriteLine("Hangfire Server started.Press any key to exit");

    Console.ReadKey();

}

5.因為上述任務的存儲是利用的Sql server實作,是以任務的運作資訊都被儲存在了SQL Server中,需要檢視對任務的運作狀态進行檢視,Hangfire也提供了一個可視化的web界面(Dashboard)。檢視過程如下:

    1)建立一個ASP.NET項目

    2)添加Hangfire支援

    3)在項目中添加OWIN startup類,然後進行配置

Hangfire實戰(一)------Hangfire+SQL Server實作簡單的任務排程

    4)啟動網站項目,輸入http://<your-site>/hangfire ,即可打開如下界面,對任務進行管理

Hangfire實戰(一)------Hangfire+SQL Server實作簡單的任務排程