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

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

程序员文章站 2022-05-03 12:05:50
1.negut引入hangfire相关包hangfire.aspnetcore,hangfire.core,hangfire.dashboard.basicauthorization,hangfire...

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持久化实现定时任务的文章就介绍到这了,更多相关.net core hangfire定时任务内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!