起因呢是公司需要定時服務,而我呢又是一個強迫症比較嚴重的人,比較喜歡統一管理,不是很喜歡傳統的定時器腳本,所以就研究了Hangfire
Hangfire支持永久化存儲也支持存儲在內存中,建議mysql 用5.7版本,在5.6版本中會出現索引錯誤的問題
上代碼 創建一個HangfireDispose配置類
public class HangfireDispose { #region HangFire配置 public HangfireDispose() { } //這里使用了.NetCore 自帶的緩存 也可以存儲在Mysql里面需要改一下方法引用即可 public static IServiceCollection HangfireServices(IServiceCollection services, IConfiguration configuration) { return services.AddHangfire(x => x.UseStorage(new MemoryStorage( new MemoryStorageOptions { JobExpirationCheckInterval = TimeSpan.FromHours(1), //- 作業到期檢查間隔(管理過期記錄)。默認值為1小時。 CountersAggregateInterval = TimeSpan.FromMinutes(5), //- 聚合計數器的間隔。默認為5分鍾。 } ))); } /// <summary> /// 配置賬號模板信息 /// </summary> /// <returns></returns> public static DashboardOptions HfDispose(IConfiguration configuration) { var filter = new BasicAuthAuthorizationFilter( new BasicAuthAuthorizationFilterOptions { SslRedirect = false, RequireSsl = false, LoginCaseSensitive = false, Users = new[] { new BasicAuthAuthorizationUser { Login = configuration["ConnectionStrings:Login"], //可視化的登陸賬號 PasswordClear = configuration["ConnectionStrings:PasswordClear"] //可視化的密碼 } } }); return new DashboardOptions { Authorization = new[] { filter } }; } /// <summary> /// 配置啟動 /// </summary> /// <returns></returns> public static BackgroundJobServerOptions jobOptions() { return new BackgroundJobServerOptions { Queues = new[] { "push", "default" },//隊列名稱,只能為小寫 WorkerCount = Environment.ProcessorCount * 5, //並發任務 ServerName = "Hangfire", //代表服務名稱 }; } #endregion #region 配置服務 public static void HangfireService() { //這里呢就是需要觸發的方法 "0/10 * * * * ? " 可以自行搜索cron表達式 代表循環的規律很簡單 //GameLenthPush代表你要觸發的類 UserGameLenthPush代表你要觸發的方法 RecurringJob.AddOrUpdate<GameLenthPush>(s => s.UserGameLenthPush(), "0/10 * * * * ? ", TimeZoneInfo.Local); } #endregion }
在Startup.cs 里面的ConfigureServices方法注入
HangfireDispose.HangfireServices(services, Configuration);
在Startup.cs 里面的Configure方法寫入
app.UseHangfireServer(HangfireDispose.jobOptions()); app.UseHangfireDashboard("/TaskManager", HangfireDispose.HfDispose(Configuration)); HangfireDispose.HangfireService();
然后新建GameLenthPush類
public IActionResult UserGameLenthPush() { return Json(new { code = 0, msg = string.Format("時間{0}", DateTime.Now.ToString()) }); }
即可完成Hangfire的部署
啟動vs 或者IIS 路徑后面添加 /TaskManager 輸入你配置的賬號密碼即可 可視化控制界面