当前位置: 移动技术网 > IT编程>开发语言>.net > AspNet MVC中使用Hangfire执行定时任务

AspNet MVC中使用Hangfire执行定时任务

2018年10月26日  | 移动技术网IT编程  | 我要评论

宝宝鞋子的织法,哈尔格林德,桂雪玉

 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(10)
            };
            app.usehangfireserver(options);

            /*每天凌晨2点运行任务,cron参数使用的是utc时间和北京时间有区别,需要转换下*/
            recurringjob.addorupdate(
                () => 执行的任务
                , cron.daily(18, 0));
        }
    }

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网