Top Nguyen Blog
Schedule Job with Hangfire

Schedule Job with Hangfire

23 December, 2016
0 Comments
6 mins
280 words

In today's post, I will introduce a newcomer, HangFire, which will definitely impress you with its persistent storage, a job/server dashboard, and the ability to run WITHOUT a Windows Service!

In many projects, you've come to a point where you need to implement background tasks, such as reminder emails, periodic data processing, and the like.  In the past, Quartz.Net was probably the most recommended component to implement background tasks. However, this solution has its own drawbacks such as requiring a Windows Service.  

In today's post, I will introduce a newcomer, HangFire, which will definitely impress you with its persistent storage, a job/server dashboard, and the ability to run WITHOUT a Windows Service!

What Is Hangfire?

An easy way to perform fire-and-forget, delayed and recurring tasks inside ASP.NET applications. No Windows Service required.

Backed by persistent storages. Open and free for commercial use.

How To Use

Fire-and-forget tasks

// Static methods are for demo purposes
BackgroundJob.Enqueue(
    () => Console.WriteLine("Simple!"));

Delayed tasks

BackgroundJob.Schedule(
    () => Console.WriteLine("Reliable!"), 
    TimeSpan.FromDays(7));

Recurring tasks

RecurringJob.AddOrUpdate(
    () => Console.WriteLine("Transparent!"), 
    Cron.Daily);

Run them inside a web app…

Forget about AppDomain unloads, Web Garden & Web Farm issues – Hangfire is reliable for ASP.NET from scratch, even on Shared Hosting!

public void Configuration(IAppBuilder app)
{
    app.UseHangfireServer();
}

… or anywhere else

In the console application, Windows Service, Azure Worker Role, etc.

using (new BackgroundJobServer())
{
    /* ... */
}

Special, you can setup dashboard with the guide by this link.

Hangfire Dashboard

An Important NuGet Note

PM> Install-Package HangFire

Another NuGet in this link.

Github link

Wiki link

Website link

Summary

Quartz.NET has more features to deal with recurring jobs: better CRON format support (including seconds and 'L' modification), more powerful triggers, calendars, etc. It is better when you have very complex scheduling logic.

And something which I didn't like about Quartz.NET was about IJob interface which should be implemented Execute method on it to run a Job .But hangFire can accept any method.

Happy Coding!