Exemplo n.º 1
0
        public static void Register(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "HangfireLogin"
            });

            GlobalConfiguration.Configuration
            .UseConsole()
            .UseSqlServerStorage("Hangfire")
            .UseNLogLogProvider()
            //.UseMemoryStorage()
            ;
            IDashboardAuthorizationFilter dashboardAuthorization = null;

#if DEV
            dashboardAuthorization = new DashboardAuthorizationFilter();
#else
            dashboardAuthorization = new DashboardBasicAuthorizationFilter();
#endif
            var dashboardOptions = new DashboardOptions
            {
                Authorization = new[]
                {
                    dashboardAuthorization
                }
            };

            app.UseHangfireDashboard("/hangfire", dashboardOptions);
            app.UseHangfireServer();
        }
        public static DashboardOptions UseAuthorization(
            [NotNull] this DashboardOptions options,
            [NotNull] IDashboardAuthorizationFilter authorizationFilter)
        {
            Check.NotNull(options, nameof(options));
            Check.NotNull(authorizationFilter, nameof(authorizationFilter));

            List <IDashboardAuthorizationFilter> filters = new List <IDashboardAuthorizationFilter>
            {
                authorizationFilter
            };

            options.Authorization = filters;

            return(options);
        }
        public static DashboardOptions AddAuthorization(
            [NotNull] this DashboardOptions options,
            [NotNull] IDashboardAuthorizationFilter authorizationFilter)
        {
            Check.NotNull(options, nameof(options));
            Check.NotNull(authorizationFilter, nameof(authorizationFilter));

            List <IDashboardAuthorizationFilter> filters = new List <IDashboardAuthorizationFilter>();

            filters.AddRange(options.Authorization);
            filters.AddIfNotContains(authorizationFilter);

            options.Authorization = filters;

            return(options);
        }
Exemplo n.º 4
0
        /// <summary>
        /// 初始化job
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="authFilter"></param>
        public static void UseHangfireJob(this IApplicationBuilder builder, IDashboardAuthorizationFilter authFilter)
        {
            var serviceProvider = builder.ApplicationServices;
            var appConfig       = serviceProvider.GetService <IConfiguration>().GetSection("Hangfire");
            var isEnable        = appConfig.GetValue <bool>("IsEnable"); //是否开启任务

            if (!isEnable)
            {
                return;
            }

            //找到所有使用的队列
            var jobList   = getJobList();
            var queueList = new List <string>()
            {
                "default"
            };
            Action <string> logQueue = (queue) =>
            {
                if (!queueList.Any(q => q == queue))
                {
                    queueList.Add(queue);
                }
            };

            foreach (Type type in jobList)
            {
                if (type.BaseType == typeof(JobBase))
                {
                    var execute   = type.GetMethod("Execute");
                    var execQueue = execute.GetCustomAttribute <QueueAttribute>();
                    if (execQueue != null)
                    {
                        logQueue(execQueue.Queue);
                    }
                }
                else
                {
                    var jobAttr = type.GetCustomAttribute <RecurringJobAttribute>();
                    if (jobAttr != null)
                    {
                        logQueue(jobAttr.Queue);
                    }
                }
            }

            //设置HangfireServer
            builder.UseHangfireServer(new BackgroundJobServerOptions
            {
                WorkerCount = Environment.ProcessorCount * 5, //并发数量
                ServerName  = appConfig["ServerName"],        //服务器名称
                Queues      = queueList.ToArray()             //队列
            });
            builder.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                Authorization = new[] { authFilter ?? new HangfireAuthorizationFilter() },
                DisplayStorageConnectionString = false,
                DashboardTitle = "任务管理"
            });

            //执行init
            foreach (Type type in jobList)
            {
                if (type.BaseType == typeof(JobBase))
                {
                    var instance = serviceProvider.GetService(type);
                    var init     = type.GetMethod("Init").MakeGenericMethod(type);
                    init.Invoke(instance, null);
                }
                else
                {
                    var jobAttr = type.GetCustomAttribute <RecurringJobAttribute>();
                    if (jobAttr == null)
                    {
                        continue;
                    }
                    var timeZone = TimeZoneHelper.GetCurrentTimeZone(); //时区
                    var methods  = type.GetMethods().Where(m => m.CustomAttributes.Any(a => a.AttributeType == typeof(CronAttribute)));
                    foreach (var method in methods)
                    {
                        var cron  = method.GetCustomAttribute <CronAttribute>().Cron; //cron表达式
                        var jobId = $"{type.ToGenericTypeString()}.{method.Name}";    //jobid
                        //作业名称
                        var nameAttr = method.GetCustomAttribute <DisplayNameAttribute>();
                        var jobName  = nameAttr != null ? nameAttr.DisplayName : jobId;
                        RecurringJob.AddOrUpdate <JobPerform>(jobId, p => p.Execute(jobName, type.AssemblyQualifiedName, method.Name), cron, timeZone, jobAttr.Queue);
                    }
                }
            }
        }