Hangfire在Aspnet中执行定时任务:
第一步:
NuGet中加入Hangfire包
第二步:
添加Owin的自启动
第三步、Hangfire的后台控制仪表盘默认情况下只能本地访问,外网访问需实现IDashboardAuthorizationFilter接口,实现方式
/// <summary>
/// Hangfire仪表盘配置授权¶
/// </summary>
public class MyDashboardAuthorizationFilter : IDashboardAuthorizationFilter
{
public bool Authorize([NotNull] DashboardContext context)
{
return HttpContext.Current.User.Identity.IsAuthenticated;
}
}
第四步、在Startup.cs里面配置Hangfire
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()
};
app.UseHangfireServer(options); /*每天凌晨2点运行任务,Cron参数使用的是UTC时间和北京时间有区别,需要转换下*/
RecurringJob.AddOrUpdate(
() => 执行的任务
, Cron.Daily(, ));
}
}