Processing Jobs in a Console Application¶
To start using Hangfire in a console application, you’ll need to install Hangfire packages to your console application first. So, use your Package Manager Console window to install it:
PM> Install-Package Hangfire.Core
Then, install the needed package for your job storage. For example, you need to execute the following command to use SQL Server:
PM> Install-Package Hangfire.SqlServer
Hangfire.Core
package is enough
Please don’t install the Hangfire
package for console applications as it is a quick-start package only and contain dependencies you may not need (for example, Microsoft.Owin.Host.SystemWeb
).
After installing packages, all you need is to create a new Hangfire Server instance and start it as written in the previous chapter. However, there are some details here:
- Since the
Start
method is non-blocking, we insert aConsole.ReadKey
call to prevent instant shutdown of an application. - The call to
Stop
method is implicit – it is made through theusing
statement.
using System;
using Hangfire;
using Hangfire.SqlServer;
namespace ConsoleApplication2
{
class Program
{
static void Main()
{
GlobalConfiguration.Configuration.UseSqlServerStorage("connection_string");
using (var server = new BackgroundJobServer())
{
Console.WriteLine("Hangfire Server started. Press any key to exit...");
Console.ReadKey();
}
}
}
}
Please use Hangfire Forum for long questions or questions with source code.