C# + Hangfire – Assign Background Task / Background Schedule Task under Web Application

C# + Hangfire – Assign Background Task / Background Schedule Task under Web Application
 
Install – Hangfire.MemoryStorage & Microsoft.Owin.Host.SystemWeb from NuGet

   Define Test Task – \Task\TestTask.cs
 
   using System;
   using System.Diagnostics;
 
   namespace WebApp.Task
   {
      public class TestTask
      {
         public static void TaskExecute()
         {
            … …
         }
      }
   }
 
   Update Web Application – Startup.cs File
 
   using System;
   using Microsoft.Owin;
   using Owin;
   using Hangfire;
   using Hangfire.MemoryStorage;
   using System.Threading.Tasks;
   using WebApp.Task;
 
   [assembly: OwinStartup(typeof(WebApp.Startup))]
   namespace WebApp
   {
      public partial class Startup
      {
         public void Configuration(IAppBuilder app)
         {
            … …
 
            GlobalConfiguration.Configuration.UseMemoryStorage();
 
            app.UseHangfireServer();
            app.UseHangfireDashboard();     /* this line can be removed for disabling Dashboard Page from the Web Application. */
 
            this.DefineAllTask();
         }
 
         public void DefineAllTask()
         {
            RecurringJob.AddOrUpdate(() => TestTask.TaskExecute(), Cron.Minutely);
         }
      }
   }
 
   Define the Task to be executed once from the Controller ActionResult
 
   public ActionResult Index()
   {
      … …
 
      BackgroundJob.Schedule(() => TestTask.TaskExecute(), TimeSpan.FromSeconds(0));
 
      … …
 
      return View();
   }
 
After the Initialization, there is a Dashboard Page from ( http://<Web Application Host>/hangfire ) URL.
The app.UseHangfireDashboard(); Line can also be removed from Startup.cs File to disable the Dashboard Page from the Web Application.

 
Reference From …