DavidSpot Blog

Developer, super curious, a dog lover, sports fan and techie guy


How to run Background Tasks in ASP.NET with HangFire

Hangfire is a set of open-source libraries that help you to create, process and manage your background jobs, i.e. operations you don't want to put in your request processing pipeline.

HangFire It's afantastic framework for background jobs in ASP.NET. It's even optionally backed by Redis, SQL Server, SQL Azure, MSMQ, or RabbitMQ for reliability.

The Hangfire documentation is amazing, really. Every open source project's document should be this polished. Heck, ASP.NET's documentation should be this good.

The best feature from Hangfire is its built in /hangfire dashboard that shows you all your scheduled, processing, succeeded and failed jobs. It's really a nice polished addition.

 

 You can enqueue "fire and forget" jobs easily and they are backed by persistent queues:

  • BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget"));

 

You can delay them...

  • BackgroundJob.Schedule(() => Console.WriteLine("Delayed"), TimeSpan.FromDays(1));

 

You can do recurrent tasks in CRON style:

  • RecurringJob.AddOrUpdate(() => Console.Write("Recurring"), Cron.Daily);

 

And you can even chain Jobs like:

  • var id = BackgroundJob.Enqueue(() => Console.Write("Hello, "));
  • BackgroundJob.ContinueWith(id, () => Console.Wirte("David");

Hangfire it’s so cool and powerfull.

Check out the Hangfire Highlighter Tutorial and the quick start tutorial for more real-world examples.