Core Concepts
Getting Started — Hangfire Documentation
Hangfire works with the majority of .NET platforms: .NET Framework 4.5.1 or later, .NET Core 1.0 or later, or any platform compatible with .NET Standard 1.3. You can integrate it with almost any application framework, including ASP.NET, ASP.NET Core, Console applications, Windows Services, WCF, as well as community-driven frameworks like Nancy or ServiceStack.
https://docs.hangfire.io/en/latest/getting-started/index.htmlMinimal Setup
dotnet add package Hangfire.Core
dotnet add package Hangfire.SqlServer
dotnet add package Microsoft.Data.SqlClientStorage
Must specify a connection string, for it to use
GlobalConfiguration.Configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage("Database=Hangfire.Sample; Integrated Security=True;");Client
The client is what writes new jobs. You pass in an expression tree with arguments that you want to pass on to your function, so for example Id . Then you also pass a DateTimeOffSet or a DateTime, to specify when you want to expression tree to execute.
Super minimal example with no execution date:
BackgroundJob.Enqueue(() => Console.WriteLine("Hello, world!"));Server
This is simply just a process that executes the Enqueued expressions. The following will start the background job server and then stop the console application from exiting by doing a Console.ReadLine.
using (new BackgroundJobServer())
{
Console.ReadLine();
}
Putting it all together for a console application
using System;
using Hangfire;
using Hangfire.SqlServer;
namespace ConsoleApplication2
{
class Program
{
static void Main()
{
GlobalConfiguration.Configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
.UseColouredConsoleLogProvider()
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage("Database=Hangfire.Sample; Integrated Security=True;");
BackgroundJob.Enqueue(() => Console.WriteLine("Hello, world!"));
using (var server = new BackgroundJobServer())
{
Console.ReadLine();
}
}
}
}