Tuesday, 23 May 2017

Hangfire in C#

Incredibly easy way to perform fire-and-forgetdelayed and recurring jobs inside ASP.NET applications. CPU and I/O intensive, long-running and short-running jobs are supported. No Windows Service / Task Scheduler required. Backed by Redis, SQL Server, SQL Azure and MSMQ.
Hangfire provides a unified programming model to handle background tasks in a reliable way and run them on shared hosting, dedicated hosting or in cloud. You can start with a simple setup and grow computational power for background jobs with time for these scenarios:
  • mass notifications/newsletters
  • batch import from xml, csv or JSON
  • creation of archives
  • firing off web hooks
  • deleting users
  • building different graphs
  • image/video processing
  • purging temporary files
  • recurring automated reports
  • database maintenance
  • …and so on

 

Installation

Hangfire is available as a NuGet package. You can install it using the NuGet Package Console window:
PM> Install-Package Hangfire
After installation, update your existing OWIN Startup file with the following lines of code.
public void Configuration(IAppBuilder app)
{
    GlobalConfiguration.Configuration.UseSqlServerStorage("<connection string or its name>");
    
    app.UseHangfireServer();
    app.UseHangfireDashboard();
}

 

 Usage:

1 - Fire-and-forget jobs

Fire-and-forget jobs are executed only once and almost immediately after creation.
var jobId = BackgroundJob.Enqueue(
    () => Console.WriteLine("Fire-and-forget!"));

 2 - Delayed jobs

Delayed jobs are executed only once too, but not immediately, after a certain time interval.
var jobId = BackgroundJob.Schedule(
    () => Console.WriteLine("Delayed!"),
    TimeSpan.FromDays(7));


3 - Recurring jobs

Recurring jobs fire many times on the specified CRON schedule.
RecurringJob.AddOrUpdate(
    () => Console.WriteLine("Recurring!"),
    Cron.Daily);


4 - Continuations

Continuations are executed when its parent job has been finished.
BackgroundJob.ContinueWith(
    jobId,
    () => Console.WriteLine("Continuation!"));


5 - Batches 

Batch is a group of background jobs that is created atomically and considered as a single entity.
var batchId = BatchJob.StartNew(x =>
{
    x.Enqueue(() => Console.WriteLine("Job 1"));
    x.Enqueue(() => Console.WriteLine("Job 2"));
});


6 - Batch Continuations 

Batch continuation is fired when all background jobs in a parent batch finished.
BatchJob.ContinueWith(batchId, x =>
{
    x.Enqueue(() => Console.WriteLine("Last Job"));
});





No comments:

Post a Comment