欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-03-17 11:40:44
Hangfire在Aspnet中执行定时任务: 第一步: NuGet中加入Hangfire包 第二步: 添加Owin的自启动 第三步、Hangfire的后台控制仪表盘默认情况下只能本地访问,外网访问需实现IDashboardAuthorizationFilter接口,实现方式 第四步、在Startu ......

 hangfire在aspnet中执行定时任务:

第一步:

  nuget中加入hangfire包

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

 

第二步:

  添加owin的自启动

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

 

 

第三步、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));
        }
    }