Last active
May 9, 2022 21:09
-
-
Save ridercz/f67885a97aef9e15ae2b7084459ae240 to your computer and use it in GitHub Desktop.
Using Hangfire in ASP.NET Core 6.0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* This is sample code for the following video: https://youtu.be/36p2-gr_iYk | |
* The following NuGet packages are needed: | |
* Hangfire | |
* Hangfire.AspNetCore | |
* Hangfire.SqlServer | |
*/ | |
using Hangfire; | |
var builder = WebApplication.CreateBuilder(args); | |
// Add Hangfire client and setup SQL Server connections | |
builder.Services.AddHangfire(options => { | |
options.UseSqlServerStorage(@"SERVER=.\SqlExpress;TRUSTED_CONNECTION=yes;DATABASE=HangfireDemo"); | |
}); | |
// Add Hangfire server | |
builder.Services.AddHangfireServer(options => { | |
options.SchedulePollingInterval = TimeSpan.FromSeconds(1); | |
}); | |
var app = builder.Build(); | |
// Enable dashboard UI at /hangfire | |
app.UseHangfireDashboard(); | |
app.MapHangfireDashboard(); | |
// Show homepage | |
app.MapGet("/", () => "Hello World!"); | |
// Get job client from IoC/DI container | |
var scope = app.Services.CreateScope(); | |
var jc = scope.ServiceProvider.GetRequiredService<IBackgroundJobClient>(); | |
// Run ASAP | |
var j1 = jc.Enqueue(() => Console.WriteLine(">>>>> Fire and forget!")); | |
// Run delayed | |
var j2 = jc.Schedule(() => Console.WriteLine(">>>>> Scheduled job"), TimeSpan.FromSeconds(5)); | |
jc.ContinueJobWith(j2, () => Console.WriteLine(">>>>> Continuation of Scheduled job.")); | |
// Run repeatedly | |
// For explanation of the Cron expression see https://en.wikipedia.org/wiki/Cron#CRON_expression | |
RecurringJob.AddOrUpdate("MyRecurringJob", () => Console.WriteLine(">>>>> Recurring job"), "*/10 * * * * *"); | |
// Run application | |
app.Run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment