使用Hangfire+.NET 6實現定時任務管理(推薦)
目錄
- 引入Nuget包和配置
- 編寫Job
- Fire and Forget
- Continuous Job
- Scehdule Job
- Recurring Job
- Run
- 長時間運行任務的并發控制???
- Job Filter記錄Job的全部事件
- 參考文章
在.NET開發生態中,我們以前開發定時任務都是用的Quartz.NET完成的。在這篇文章里,記錄一下另一個很強大的定時任務框架的使用方法:Hangfire。兩個框架各自都有特色和優勢,可以根據參考文章里張隊的那篇文章對兩個框架的對比來進行選擇。
引入Nuget包和配置
引入Hangfire相關的Nuget包:
Hangfire.AspNetCoreHangfire.MemoryStorageHangfire.Dashboard.Basic.Authentication
并對Hangfire進行服務配置:
builder.Services.AddHangfire(c =>{ // 使用內存數據庫演示,在實際使用中,會配置對應數據庫連接,要保證該數據庫要存在 c.UseMemoryStorage();});// Hangfire全局配置GlobalConfiguration.Configuration .UseColouredConsoleLogProvider() .UseSerilogLogProvider() .UseMemoryStorage() .WithJobExpirationTimeout(TimeSpan.FromDays(7));// Hangfire服務器配置builder.Services.AddHangfireServer(options =>{ options.HeartbeatInterval = TimeSpan.FromSeconds(10);});
使用Hangfire中間件:
// 添加Hangfire Dashboardapp.UseHangfireDashboard();app.UseAuthorization();app.MapControllers();// 配置Hangfire Dashboard路徑和權限控制app.MapHangfireDashboard("/hangfire", new DashboardOptions{ AppPath = null, DashboardTitle = "Hangfire Dashboard Test", Authorization = new [] {new HangfireCustomBasicAuthenticationFilter{ User = app.Configuration.GetSection("HangfireCredentials:UserName").Value, Pass = app.Configuration.GetSection("HangfireCredentials:Password").Value} }});
對應的配置如下:
appsettings.json
"HangfireCredentials": { "UserName": "admin", "Password": "admin@123"}
編寫Job
Hangfire免費版本支持以下類型的定時任務:
- 周期性定時任務:
Recurring Job
- 執行單次任務:
Fire and Forget
- 連續順序執行任務:
Continouus Job
- 定時單次任務:
Schedule Job
Fire and Forget
這種類型的任務一般是在應用程序啟動的時候執行一次結束后不再重復執行,最簡單的配置方法是這樣的:
using Hangfire;BackgroundJob.Enqueue(() => Console.WriteLine("Hello world from Hangfire with Fire and Forget job!"));
Continuous Job
這種類型的任務一般是進行順序型的任務執行調度,比如先完成任務A,結束后執行任務B:
var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("Hello world from Hangfire with Fire and Forget job!"));// Continuous Job, 通過指定上一個任務的Id來跟在上一個任務后執行BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine("Hello world from Hangfire using continuous job!"));
Scehdule Job
這種類型的任務是用于在未來某個特定的時間點被激活運行的任務,也被叫做Delayed Job
:
var jobId = BackgroundJob.Enqueue(() => Console.WriteLine("Hello world from Hangfire with Fire and Forget job!"));// Continuous Job, 通過指定上一個任務的Id來跟在上一個任務后執行BackgroundJob.ContinueJobWith(jobId, () => Console.WriteLine("Hello world from Hangfire using continuous job!"));
Recurring Job
這種類型的任務應該是我們最常使用的類型,使用Cron表達式來設定一個執行周期時間,每到設定時間就被激活執行一次。對于這種相對常見的場景,我們可以演示一下使用單獨的類來封裝任務邏輯:
IJob.cs
namespace HelloHangfire;public interface IJob{ public Task<bool> RunJob();}
Job.cs
using Serilog;namespace HelloHangfire;public class Job : IJob{ public async Task<bool> RunJob() {Log.Information($"start time: {DateTime.Now}");// 模擬任務執行await Task.Delay(1000);Log.Information("Hello world from Hangfire in Recurring mode!");Log.Information($"stop time: {DateTime.Now}");return true; }}
在Program.cs
中使用Cron來注冊任務:
builder.Services.AddTransient<IJob, Job>();// ...var app = builder.Build();// ...var JobService = app.Services.GetRequiredService<IJob>();// Recurring jobRecurringJob.AddOrUpdate("Run every minute", () => JobService.RunJob(), "* * * * *");
Run
控制臺輸出:
info: Hangfire.BackgroundJobServer[0]
Starting Hangfire Server using job storage: 'Hangfire.MemoryStorage.MemoryStorage'
info: Hangfire.BackgroundJobServer[0]
Using the following options for Hangfire Server:
Worker count: 20
Listening queues: 'default'
Shutdown timeout: 00:00:15
Schedule polling interval: 00:00:15
info: Hangfire.Server.BackgroundServerProcess[0]
Server b8d0de54-caee-4c5e-86f5-e79a47fad51f successfully announced in 11.1236 ms
info: Hangfire.Server.BackgroundServerProcess[0]
Server b8d0de54-caee-4c5e-86f5-e79a47fad51f is starting the registered dispatchers: ServerWatchdog, ServerJobCancellationWatcher, ExpirationManager, CountersAggregator, Worker, DelayedJobScheduler, RecurringJobScheduler...
info: Hangfire.Server.BackgroundServerProcess[0]
Server b8d0de54-caee-4c5e-86f5-e79a47fad51f all the dispatchers started
Hello world from Hangfire with Fire and Forget job!
Hello world from Hangfire using continuous job!
info: Microsoft.Hosting.Lifetime[14]
Now listening on: https://localhost:7295
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5121
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/yu.li1/Projects/asinta/Net6Demo/HelloHangfire/HelloHangfire/
[16:56:14 INF] start time: 02/25/2022 16:56:14
[16:57:14 INF] start time: 02/25/2022 16:57:14
[16:57:34 INF] Hello world from Hangfire in Recurring mode!
[16:57:34 INF] stop time: 02/25/2022 16:57:34
通過配置的dashboard來查看所有的job運行的狀況:
長時間運行任務的并發控制???
從上面的控制臺日志可以看出來,使用Hangfire進行周期性任務觸發的時候,如果執行時間大于執行的間隔周期,會產生任務的并發。如果我們不希望任務并發,可以在配置并發數量的時候配置成1,或者在任務內部去判斷當前是否有相同的任務正在執行,如果有則停止繼續執行。但是這樣也無法避免由于執行時間過長導致的周期間隔不起作用的問題,比如我們希望不管在任務執行多久的情況下,前后兩次激活都有一個固定的間隔時間,這樣的實現方法我還沒有試出來。有知道怎么做的小伙伴麻煩說一下經驗。
Job Filter記錄Job的全部事件
有的時候我們希望記錄Job運行生命周期內的所有事件,可以參考官方文檔:Using job filters來實現該需求。
參考文章
關于Hangfire更加詳細和生產環境的使用,張隊寫過一篇文章:Hangfire項目實踐分享。
到此這篇關于使用Hangfire+.NET 6實現定時任務管理的文章就介紹到這了,更多相關.NET 定時任務管理內容請搜索以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持!