Hangfire簡介
Hangfire是一個開源的任務調度框架,它內置集成了控制頁面,很方便我們查看,控制作業的運行;對於運行失敗的作業自動重試運行。它支持永久性存儲,支持存儲於mssql,mysql,mongodb,redis等
想了解更多關於Hangfire,請移步hangfire官網https://www.hangfire.io/
簡單使用Hangfire
第一步:創建WebApi項目承載任務調度
引入Hangfire和Hangfire.MySql.Core(因為我使用的mysql作為定時任務數據持久化的數據庫,所以需要Hangfire.MySql.Core)
修改appsettings.json配置文件,添加持久化作業數據的數據庫連接
"ConnectionStrings": { "DiseaseJobConnection": "Server=localhost;port=3306;Database=diseasejob;User Id=root;password=root23456;Allow User Variables=True" },
第二步、創建作業業務類
/// <summary> /// 疫情業務類 /// </summary> public class DiseaseService : IDiseaseService { private IHttpClientFactory _httpClientFactory = null; // private DiseaseDataContext _diseaseDataContext = null; /// <summary> /// /// </summary> /// <param name="httpClientFactory"></param> /// <param name="diseaseDataContext"></param> public DiseaseService(IHttpClientFactory httpClientFactory) //, DiseaseDataContext diseaseDataContext) { this._httpClientFactory = httpClientFactory; //_diseaseDataContext = diseaseDataContext; } /// <summary> /// 同步疫情 /// </summary> /// <returns></returns> public async Task<string> SyncDiseaseData() { //TODO同步疫情數據
return "";
}
第三步、在startup.cs中注入Hangfire
ConfigureServices方法中添加
services.AddHttpClient(); //注入HttpClient #region hangfire var storage = new MySqlStorage(Configuration.GetConnectionString("DiseaseJobConnection") , new MySqlStorageOptions { PrepareSchemaIfNecessary = true, TablePrefix = "Disease" }); //GlobalConfiguration.Configuration.UseStorage(new MySqlStorage(storage, new MySqlStorageOptions //{ // TransactionIsolationLevel = IsolationLevel.ReadCommitted, // 事務隔離級別。默認值為讀提交。 // QueuePollInterval = TimeSpan.FromSeconds(15), // 作業隊列輪詢間隔。默認值為15秒 // JobExpirationCheckInterval = TimeSpan.FromHours(1), // 作業過期檢查間隔(管理過期記錄)。默認為1小時 // CountersAggregateInterval = TimeSpan.FromMinutes(5), // 間隔到聚合計數器。默認為5分鍾 // PrepareSchemaIfNecessary = true, // 如果設置為true,則創建數據庫表。默認值為true // DashboardJobListLimit = 50000, // 儀表板作業列表上限。默認值為50000 // TransactionTimeout = TimeSpan.FromMinutes(1), // 事務超時。默認為1分鍾 //})); services.AddHangfire(p => p.UseStorage(storage)); #endregion services.AddScoped<DiseaseService>(); //注入業務
在Configure方法中
//hangfire app.UseHangfireServer(); app.UseHangfireDashboard(); //作業 RecurringJob.AddOrUpdate<DiseaseService>("SyncDiseaseInformation", p => p.SyncDiseaseData(), "0 9,12,18,0 * * ?");
-------------------------------
運行程序后切換到hangfire管理頁面如下圖: