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)); } }