Hangfire is a great library to schedule and execute asynchronous work in a web application. One of the things I like about this library is that you can start with a simple background process inside the Application Pool and when your jobs get larger(and take more time) you can move them to a separate process.
Here are the steps to move your Hangfire jobs outside your web application:
- Step 1 – Change the Hangfire configuration inside your web app to disable the Hangfire server functionality(note that the job information is stored inside a database):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public partial class Startup | |
{ | |
public void Configuration(IAppBuilder app) | |
{ | |
ConfigureAuth(app); | |
app.UseHangfire(config => | |
{ | |
config.UseSqlServerStorage("DefaultConnection"); | |
//Comment out the use server method to only schedule the work | |
// config.UseServer(); | |
}); | |
} | |
} |
- Step 2 –Schedule your jobs(like you did before):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ScheduleJobController : Controller | |
{ | |
// GET: ScheduleJob | |
public ActionResult Index() | |
{ | |
return View(); | |
} | |
[HttpPost] | |
public ActionResult Index(ScheduleJob job) | |
{ | |
BackgroundJob.Enqueue(() => job.CreateCustomer(job.Customer)); | |
return RedirectToAction("Index"); | |
} | |
} |
- Step 3 – Inside another project, a console application in this case, you can host the Hangfire server:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var storage = new SqlServerStorage("DefaultConnection"); | |
var options = new BackgroundJobServerOptions(); | |
using (var server = new BackgroundJobServer(options, storage)) | |
{ | |
server.Start(); | |
Console.WriteLine("Hangfire Server started. Press any key to exit..."); | |
Console.ReadKey(); | |
} | |
} | |
} |