Scheduler in .Net Core 2.1 Hangfire tutorial

Steven(Liang) Chen
Sep 25, 2018 · 3 min read
Image for post
Image for post
Hangfire Dashboard

Background:

I used to setup my project scheduler by using windows service, mostly sending emails, then I find a better library to do this task — Hangfire. There are multiple reasons, the first is Hangfire is free!!! and then it provide dashboard to monitor and control your scheduled tasks, the last point is it is easy to setup.

Options:

Before we get into this Hangfire tutorial make sure you compare all the libraries otherwise you need to refactor your application which is waste of time. After compare these options and ask a friend, I decided to use Hangfire to handle the scheduling emails.

<PackageReference Include="Hangfire.AspNetCore" Version="1.6.20" />
<PackageReference Include="Hangfire.Dashboard.Authorization" Version="2.1.0" />
<PackageReference Include="Hangfire.SqlServer" Version="1.6.20" />
public void ConfigureServices(IServiceCollection services)
services.AddHangfire(config =>
config.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")));
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
app.UseHangfireDashboard();
app.UseHangfireServer();
Image for post
Image for post
Hangfire
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{



app.UseAuthentication();
app.UseHangfireServer();
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
Authorization = new[] { new HangfireAuthorizationFilter() },
});

app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/chat");
routes.MapHub<NotificationHub>("/notification");
});

app.UseMvc(routes =>
{
routes.MapRoute(
"default",
"{controller=Home}/{action=Index}/{id?}");
});

}



public class HangfireAuthorizationFilter : IDashboardAuthorizationFilter
{

public bool Authorize(DashboardContext context)
{
var httpContext = context.GetHttpContext();

return httpContext.User.IsAdmin();
}

}

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store