다음을 통해 공유


ASP.NET MVC HangFire - Execute Jobs in Background using SQL Server

Introduction

This article walks you through the configuration of HangFire.

"An easy way to perform fire-and-forget, delayed and recurring tasks inside ASP.NET applications" - http://hangfire.io/

We can easily configure different types of jobs (recurring, schedule or fire and forget)

Step By Step

STEP 1 - Create ASP.NET Web Application

  • Open Visual Studio 2015 and create a new project of type ASP.NET Web Application.
  • On this project create a solution called HangFire.

https://code.msdn.microsoft.com/site/view/file/142546/1/1.png

  • Press OK, and a new screen will appear, with several template options to use on our project.
  • Select the option MVC.

 

STEP 2 - Install NuGet

In order to use HangFire we need to install a NuGet package.

We can install using the Package Manager Console

  • PM> Install-Package HangFire -Version 1.4.6

Or using the Visual Studio NuGet Management

https://code.msdn.microsoft.com/site/view/file/142550/1/3.png

STEP 3 - Configure Startup class

Need to provide connection string to our database.

using Hangfire; 
using Microsoft.Owin; 
using Owin; 
using System; 
  
[assembly: OwinStartupAttribute(typeof(HangFire.Startup))] 
namespace HangFire 
{ 
    public partial  class Startup 
    { 
        public void  Configuration(IAppBuilder app) 
        { 
            ConfigureAuth(app); 
  
            GlobalConfiguration.Configuration 
                .UseSqlServerStorage("connectionString"); 
  
            BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget!")); 
  
            app.UseHangfireDashboard(); 
            app.UseHangfireServer(); 
        } 
    } 
}

 

STEP 4 - Run

Run the application by using the address of it followed by /hangfire, like on the image below.

https://code.msdn.microsoft.com/site/view/file/142551/1/4.png

When we run this address for the first time, a new table will be created in our database.

https://code.msdn.microsoft.com/site/view/file/142552/1/5.png

Resources

Some good resources can be found here: