How to use Hangfire in C#
By FoxLearn 1/7/2025 3:06:52 AM 206
Hangfire is a strong alternative to Quartz.Net for job scheduling because it doesn't require a Windows Service, unlike Quartz.Net.
The next step is to install and configure Hangfire in your application.
You can install Hangfire via the NuGet Package Manager in Visual Studio, or use the Package Manager Console. By default, Hangfire uses SQL Server to store scheduling data, but you can switch to Redis by installing Hangfire.Redis if needed.
Before using Hangfire, you must configure persistent storage by creating a database and specify the connection string with the appropriate credentials in your application's configuration file. You don't need to manually create tables in the database Hangfire will automatically generate them for you.
Once the database and connection string are set up, modify the Startup.cs
file to include the necessary connection details.
using Hangfire; using Microsoft.Owin; using Owin; using System; [assembly: OwinStartupAttribute(typeof(HangFire.Startup))] namespace HangFire { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); GlobalConfiguration.Configuration.UseSqlServerStorage("DefaultConnection"); BackgroundJob.Enqueue(() => Console.WriteLine("Getting Started with HangFire!")); app.UseHangfireDashboard(); app.UseHangfireServer(); } } }
Now, when you run the application and append "/hangfire" to the URL, you will see the Hangfire dashboard. The first time you run the application, Hangfire will create several tables in the database, including AggregatedCounter
, Counter
, Job
, JobQueue
, Server
, and others.
Creating a fire-and-forget background job is simple. Use the Enqueue()
method of the BackgroundJob
class:
BackgroundJob.Enqueue(() => Console.WriteLine("This is a fire-and-forget job that would run in the background."));
For delayed background jobs, use the Schedule()
method to set a delay before execution:
BackgroundJob.Schedule(() => Console.WriteLine("This background job will execute after a delay."), TimeSpan.FromMilliseconds(1000));
To create recurring jobs that execute at regular intervals, use the RecurringJob
class.
For example, to create a job that runs every minute:
RecurringJob.AddOrUpdate(() => Console.WriteLine("This job will execute once every minute"), Cron.Minutely);
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#