Hangfire在Aspnet中執行定時任務:sql
第一步:app
NuGet中加入Hangfire包sqlserver
第二步:ui
添加Owin的自啓動spa
第三步、Hangfire的後臺控制儀表盤默認狀況下只能本地訪問,外網訪問需實現IDashboardAuthorizationFilter接口,實現方式3d
/// <summary> /// Hangfire儀表盤配置受權¶ /// </summary> public class MyDashboardAuthorizationFilter : IDashboardAuthorizationFilter { public bool Authorize([NotNull] DashboardContext context) { return HttpContext.Current.User.Identity.IsAuthenticated; } }
第四步、在Startup.cs裏面配置Hangfirecode
public class Startup { public void Configuration(IAppBuilder app) { //使用sqlserver持久化 GlobalConfiguration.Configuration .UseSqlServerStorage("DefaultConnection"); //控制儀表盤的訪問路徑和受權配置 app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new[] { new MyDashboardAuthorizationFilter() } }); //指定輪詢調度的間隔,根據實際狀況設置 var options = new BackgroundJobServerOptions { SchedulePollingInterval = TimeSpan.FromMinutes(10) }; app.UseHangfireServer(options); /*天天凌晨2點運行任務,Cron參數使用的是UTC時間和北京時間有區別,須要轉換下*/ RecurringJob.AddOrUpdate( () => 執行的任務 , Cron.Daily(18, 0)); } }