Hangfire with MySql & ASP.NET

Published on

I’m going to describe how I implemented Hangfire with MySql in an ASP.NET 5 web application.

What is hangfire ?

Hangfire is an open-source framework for .NET apps that helps create and manage both scheduled and background tasks.

The typical setup looks something like:

  • A data storage layer.
  • Processing server(s).

Date storage: I’m using MySql for data storage, however there are extensions availible for other database types. Sqlite, SQL Server or Redis for example.

Processing: It’s possible to configure Hangfire with a farm of processing servers, however that it outside the scope of this post. We’re only going to have one server.

MySql preperation

You must have a MySql server setup with a database that will hold data stored by Hangfire. You don’t need to create individual tables inside the database, since Hangfire will make those arrangements.

I’m naming my database “Hangfire”. This will need to be configured within a connection string inside your application. I use the appsettings.json file.

  "ConnectionStrings": {
    "HangfireDb": "server=localhost;database=hangfire;uid=myuser;pwd=mypassword;Allow User Variables=True"
  },

Nuget package

Install the following Nuget packages. These add the Hangfire framework and the MySql extension to your project.

Hangfire.AspNetCore Hangfire.Core Hangfire.MySqlStorage

Startup.cs

Now add the following code to the ConfigureServices method inside your Startup.cs file.

        // Add Hangfire services.
        string hangfireConnectionString = Configuration.GetConnectionString("HangfireDb");
        services.AddHangfire(configuration => configuration
            .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
            .UseSimpleAssemblyNameTypeSerializer()
            .UseRecommendedSerializerSettings()
            .UseStorage(
                new MySqlStorage(
                    hangfireConnectionString,
                    new MySqlStorageOptions
                    {
                        QueuePollInterval = TimeSpan.FromSeconds(10),
                        JobExpirationCheckInterval = TimeSpan.FromHours(1),
                        CountersAggregateInterval = TimeSpan.FromMinutes(5),
                        PrepareSchemaIfNecessary = true,
                        DashboardJobListLimit = 25000,
                        TransactionTimeout = TimeSpan.FromMinutes(1),
                        TablesPrefix = "Hangfire",
                    }
                )
            ));

        // Add the processing server as IHostedService
        services.AddHangfireServer(options => options.WorkerCount = 1);

If you want to also add the Hangfire dashboard, add the following to your Configure method.

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
                endpoints.MapHangfireDashboard("/hangfire", new DashboardOptions
                {
                    Authorization = new[] { new HangfireAuthorizationFilter() },
                    IgnoreAntiforgeryToken = true
                });
            });

And that’s it. You should be all set to start registering jobs with Hangfire.


Article Categories: # hangfire # c# # .net # mysql
Date Published: Jun 28, 2021

About

A tech blog by Andy P. I talk about coding, enterprise software development, tech, games design & other things that interest me.

Teambuilding & fitness

Our friends at Company Fitness League are building fun platform for getting fit with your colleagues!