codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Schedule Cron Jobs using HostedService in ASP.NET Core

Changhui Xu
codeburst
Published in
7 min readDec 31, 2019

--

I have written a blog post about scheduling background jobs using Hangfire because most .NET developers use either Hangfire or Quartz.NET to schedule background tasks. However, with the release of .NET Core 2.1, background tasks can be implemented as hosted services. Let’s explore it!

In this blog post, we will go over the use case of scheduling cron jobs using a customized HostedService in an ASP.NET Core Web API project. The following screen recording shows the runtime logging for the final application, which has three background tasks running at every 5 minutes, every 1 minute, and every day at 12:50 PM.

The job schedules are defined by Cron Expressions. For example, the cron expression */5 * * * * represents a schedule of every 5 minutes, the cron expression * * * * * defines a minute-by-minute schedule, and the cron expression 50 12 * * * means 12:50 PM daily.

The complete project is located at this GitHub repository. You can follow the project to implement your own Cron Job Services, and schedule the jobs to run at any time or within any interval. If you find potential improvements, please leave a comment below or create a PR in my GitHub repository. Now, let’s dive in.

Create an ASP.NET Core Web Project

In this project, we will work on an ASP.NET Core Web API project. The reason why we create a Web API project is to demonstrate the possibilities of hosting cron jobs in an ASP.NET Core web application. You can also follow the tutorial in Microsoft Docs, and create a Console project using the Worker Service template. The goal is to have a project that references the NuGet package Microsoft.Extensions.Hosting, which includes the IHostService, BackgroundService, and so on. All ASP.NET Core web project templates and the Worker Service template have already included this NuGet package.

In order to parse the cron expressions, we add a NuGet package Cronos to the Web API project. The Cronos package is a lightweight but full-fledged library for parsing cron expressions and calculating next occurrences with time zones…

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Changhui Xu

Lead Application Developer. MBA. I write blogs about .NET, Angular, JavaScript/TypeScript, Docker, AWS, DDD, and many others.

Responses (20)

Write a response