.net core基于Hangfire+Mysql持久化怎么实现定时任务配置

发布时间:2021-07-20 10:28:19 作者:chen
来源:亿速云 阅读:335

本篇内容主要讲解“.net core基于Hangfire+Mysql持久化怎么实现定时任务配置”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“.net core基于Hangfire+Mysql持久化怎么实现定时任务配置”吧!

1.negut引入hangfire相关包

Hangfire.AspNetCore,Hangfire.Core,Hangfire.Dashboard.BasicAuthorization,Hangfire.MySqlStorage

.net core基于Hangfire+Mysql持久化怎么实现定时任务配置

2.Appsetting 配置hangfire资源

"HangFire": {
    "Connection": "Server=127.0.0.1;uid=root;pwd=wakamysql666;database=Hangfire_DB;AllowLoadLocalInfile=true;Allow User Variables=True;",
    "pathMatch": "/hangfire",
    "Login": "login",
    "PasswordClear": "pwd"
  },

3.自定义扩展类

/// <summary>
    ///     任务调度
    /// </summary>
    public static class HangfireSetup
    {
        public static void AddHangfireSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            if (services == null) throw new ArgumentNullException(nameof(services));
            services.AddHangfire(configuration => configuration
                .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)//此方法 只初次创建数据库使用即可
                .UseSimpleAssemblyNameTypeSerializer()
                .UseRecommendedSerializerSettings()
                .UseStorage(new MySqlStorage(Appsettings.app("HangFire", "Connection"), new MySqlStorageOptions
                {
                    TransactionIsolationLevel =
                        (IsolationLevel?) System.Data.IsolationLevel.ReadCommitted, //事务隔离级别。默认是读取已提交
                    QueuePollInterval = TimeSpan.FromSeconds(15), //- 作业队列轮询间隔。默认值为15秒。
                    JobExpirationCheckInterval = TimeSpan.FromHours(1),
                    CountersAggregateInterval = TimeSpan.FromMinutes(5),
                    PrepareSchemaIfNecessary = false, // 如果设置为true,则创建数据库表。默认是true
                    DashboardJobListLimit = 50000,
                    TransactionTimeout = TimeSpan.FromMinutes(1),
                    TablesPrefix = "Hangfire"
                })));
            services.AddHangfireServer();
        }
    }

4.在startupConfigureServices注入扩展

   services.AddHangfireSetup();//任务调度

.net core基于Hangfire+Mysql持久化怎么实现定时任务配置

5.配置MIddleware

//任务调度中间件
    public static class HangfireMiddleware
    {
        public static void UseHangfireMiddleware(this IApplicationBuilder app)
        {
            if (app == null) throw new ArgumentNullException(nameof(app));
            app.UseHangfireServer(); //配置服务//ConfigureOptions()
            app.UseHangfireDashboard(Appsettings.app("HangFire", "pathMatch"), HfAuthor()); //配置面板
            //BackgroundJob.Enqueue(() => Console.WriteLine("Hello world from Hangfire!"));            
            HangfireService(); //配置各个任务
        }

        /// <summary>
        ///     配置账号模板信息
        /// </summary>
        /// <returns></returns>
        public static DashboardOptions HfAuthor()
        {
            var filter = new BasicAuthAuthorizationFilter(
                new BasicAuthAuthorizationFilterOptions
                {
                    SslRedirect = false,
                    RequireSsl = false,
                    LoginCaseSensitive = false,
                    Users = new[]
                    {
                        new BasicAuthAuthorizationUser
                        {
                            Login = Appsettings.app("HangFire", "Login"), //可视化的登陆账号
                            PasswordClear = Appsettings.app("HangFire", "PasswordClear") //可视化的密码
                        }
                    }
                });
            return new DashboardOptions
            {
                Authorization = new[] {filter}
            };
        }

        /// <summary>
        ///     配置启动
        /// </summary>
        /// <returns></returns>
        public static BackgroundJobServerOptions ConfigureOptions()
        {
            return new()
            {
                Queues = new[] {"Job", nameof(HangfireConfigureQueue.picturetooss)}, //队列名称,只能为小写
                WorkerCount = Environment.ProcessorCount * 5, //并发任务
                ServerName = "HangfireServer" //代表服务名称
            };
        }

        #region 配置服务

        public static void HangfireService()
        {
            // "0 0 1 * * ? " 每天凌晨一点执行阿里云OSS
            RecurringJob.AddOrUpdate<IOrderItemInfoService>(_ => _.JobOSS(), "0 0 1 * * ? ", TimeZoneInfo.Local,
                nameof(HangfireConfigureQueue.picturetooss));

            // "0 0 1 * * ? " 每天早上七点执行定时任务更新汇率
            RecurringJob.AddOrUpdate<ICurrencyInfosService>(_ => _.UpdateRateByJob(), "0 0 7 * * ? ",
                TimeZoneInfo.Local, nameof(HangfireConfigureQueue.picturetooss));
        }

        #endregion
    }

6.startupConfigure配置使用中间件

 app.UseHangfireMiddleware();//Job

效果图:

.net core基于Hangfire+Mysql持久化怎么实现定时任务配置

.net core基于Hangfire+Mysql持久化怎么实现定时任务配置

结语:到此hangfire实现定时任务的配置已经全部完成。

到此,相信大家对“.net core基于Hangfire+Mysql持久化怎么实现定时任务配置”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

推荐阅读:
  1. 如何在ASP.NET CORE中实现一个Hangfire功能
  2. ASP.NET Core中的Identity怎么用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

mysql hangfire

上一篇:Linux测试工具route的配置及实现方法

下一篇:怎么修改gazebo物理参数

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》