.net core implementation of timed task configuration method based on hangfire+mysql persistence

Time:2022-8-3

1. Negut introduces hangfire related packages

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

2. Appsetting configuring hangfire resources


"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. User defined extension class

/// <summary>
    ///Task scheduling
    /// </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) // this method is only used to create a database for the first time
                .UseSimpleAssemblyNameTypeSerializer()
                .UseRecommendedSerializerSettings()
                .UseStorage(new MySqlStorage(Appsettings.app("HangFire", "Connection"), new MySqlStorageOptions
                {
                    TransactionIsolationLevel =
                        (IsolationLevel?)  System.Data.IsolationLevel. Readcommitted, // transaction isolation level. The default is read committed
                    QueuePollInterval = TimeSpan. Fromseconds (15), // - job queue polling interval. The default value is 15 seconds.
                    JobExpirationCheckInterval = TimeSpan.FromHours(1),
                    CountersAggregateInterval = TimeSpan.FromMinutes(5),
                    Prepareschemaifnecessary = false, // if set to true, the database table will be created. The default is true
                    DashboardJobListLimit = 50000,
                    TransactionTimeout = TimeSpan.FromMinutes(1),
                    TablesPrefix = "Hangfire"
                })));
            services.AddHangfireServer();
        }
    }

4. Inject extension in startupconfigureservices

services.AddHangfireSetup();// task scheduling 

5. Configure Middleware

//Task scheduling Middleware
    public static class HangfireMiddleware
    {
        public static void UseHangfireMiddleware(this IApplicationBuilder app)
        {
            if (app == null) throw new ArgumentNullException(nameof(app));
            app. UseHangfireServer(); // Configure service // configureoptions()
            app.UseHangfireDashboard(Appsettings.app("HangFire", "pathMatch"), HfAuthor()); // Configuration panel
            //BackgroundJob.Enqueue(() => Console.WriteLine("Hello world from Hangfire!"));            
            HangfireService(); // Configure each task
        }

        /// <summary>
        ///Configure account template information
        /// </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"), // visual login account
                            PasswordClear = Appsettings. App ("hangfire", "passwordclear") // visual password
                        }
                    }
                });
            return new DashboardOptions
            {
                Authorization = new[] {filter}
            };
        }

        /// <summary>
        ///Configure startup
        /// </summary>
        /// <returns></returns>
        public static BackgroundJobServerOptions ConfigureOptions()
        {
            return new()
            {
                Queues = new[] {"job", NAMEOF (hangfireconfigurequeue.picturetooss)}, // queue name, which can only be lowercase
                WorkerCount = Environment. Processorcount * 5, // concurrent tasks
                Servername = "hangfireserver" // represents the service name
            };
        }

        #Region configuration service

        public static void HangfireService()
        {
            // "0 0 1 * * ? "  Implement Alibaba cloud OSS at 1 a.m. every day
            RecurringJob.AddOrUpdate<IOrderItemInfoService>(_ => _.JobOSS(), "0 0 1 * * ? ", TimeZoneInfo.Local,
                nameof(HangfireConfigureQueue.picturetooss));

            // "0 0 1 * * ? "  Carry out a regular task to update the exchange rate at 7:00 every morning
            RecurringJob.AddOrUpdate<ICurrencyInfosService>(_ => _.UpdateRateByJob(), "0 0 7 * * ? ",
                TimeZoneInfo.Local, nameof(HangfireConfigureQueue.picturetooss));
        }

        #endregion
    }

6. Startupconfigure configuration uses Middleware


 app.UseHangfireMiddleware();//Job

design sketch:

Conclusion: the configuration of this hangfire implementation timing task has been completed.

This is about Net core based on hangfire+mysql persistence to achieve scheduled tasks, this is the article, more related Net core hangfire scheduled task content, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!

Recommended Today

Develop your own cool color selector using HTML5 Technology

You may have seen many color selectors developed using jquery/js. Today, we will use HTML5 technology to implement a better color selector by ourselves. Hope you like it! Copy code The code is as follows: <!–preview element –> <div></div> <!– colorpicker element –> <div style=”display:none”> <canvas var=”1″ width=”300″ height=”300″></canvas> <div> <div><label>R</label> <input type=”text” /></div> <div><label>G</label> […]