溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

.net core基于Hangfire+Mysql持久化怎么實現(xiàn)定時任務配置

發(fā)布時間:2021-07-20 10:28:19 來源:億速云 閱讀:326 作者:chen 欄目:開發(fā)技術

本篇內(nèi)容主要講解“.net core基于Hangfire+Mysql持久化怎么實現(xiàn)定時任務配置”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“.net core基于Hangfire+Mysql持久化怎么實現(xiàn)定時任務配置”吧!

1.negut引入hangfire相關包

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

.net core基于Hangfire+Mysql持久化怎么實現(xiàn)定時任務配置

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>
    ///     任務調(diào)度
    /// </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)//此方法 只初次創(chuàng)建數(shù)據(jù)庫使用即可
                .UseSimpleAssemblyNameTypeSerializer()
                .UseRecommendedSerializerSettings()
                .UseStorage(new MySqlStorage(Appsettings.app("HangFire", "Connection"), new MySqlStorageOptions
                {
                    TransactionIsolationLevel =
                        (IsolationLevel?) System.Data.IsolationLevel.ReadCommitted, //事務隔離級別。默認是讀取已提交
                    QueuePollInterval = TimeSpan.FromSeconds(15), //- 作業(yè)隊列輪詢間隔。默認值為15秒。
                    JobExpirationCheckInterval = TimeSpan.FromHours(1),
                    CountersAggregateInterval = TimeSpan.FromMinutes(5),
                    PrepareSchemaIfNecessary = false, // 如果設置為true,則創(chuàng)建數(shù)據(jù)庫表。默認是true
                    DashboardJobListLimit = 50000,
                    TransactionTimeout = TimeSpan.FromMinutes(1),
                    TablesPrefix = "Hangfire"
                })));
            services.AddHangfireServer();
        }
    }

4.在startupConfigureServices注入擴展

   services.AddHangfireSetup();//任務調(diào)度

.net core基于Hangfire+Mysql持久化怎么實現(xiàn)定時任務配置

5.配置MIddleware

//任務調(diào)度中間件
    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, //并發(fā)任務
                ServerName = "HangfireServer" //代表服務名稱
            };
        }

        #region 配置服務

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

            // "0 0 1 * * ? " 每天早上七點執(zhí)行定時任務更新匯率
            RecurringJob.AddOrUpdate<ICurrencyInfosService>(_ => _.UpdateRateByJob(), "0 0 7 * * ? ",
                TimeZoneInfo.Local, nameof(HangfireConfigureQueue.picturetooss));
        }

        #endregion
    }

6.startupConfigure配置使用中間件

 app.UseHangfireMiddleware();//Job

效果圖:

.net core基于Hangfire+Mysql持久化怎么實現(xiàn)定時任務配置

.net core基于Hangfire+Mysql持久化怎么實現(xiàn)定時任務配置

結語:到此hangfire實現(xiàn)定時任務的配置已經(jīng)全部完成。

到此,相信大家對“.net core基于Hangfire+Mysql持久化怎么實現(xiàn)定時任務配置”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關內(nèi)容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI