Schedule Background Jobs with Quartz.NET
What is Quartz.NET
There are many ways to schedule background jobs, but two are particularly well-known. Quartz and Hangfire. I talked about Hangfire in a recent LinkedIn post. Today we are going to learn about Quartz.
Quartz.NET is used for scheduling jobs with some additional features over Hangfire. CRON triggers, calendar events, and simple events are all supported.
How to use it ?
- Install Packages
- Create Job
- Configure Program.cs
Step 1 : Install Packages
Install following packages from Nuget Package Manager
- Microsoft.Data.SqlClient
- Microsoft.Extensions.Hosting
- Quartz
- Quartz.Extensions.Hosting
- Quartz.Serialization.Json
Step 2 : Create Job
public class NewsletterJob : IJob
{
public async Task Execute(IJobExecutionContext context)
{
await Console.Out.WriteLineAsync("Newsletter Job");
}
}
Step 3 : Configure Program.cs
I have created an extension method for IServiceCollections and called it in Program.cs like this :
using Quartz.NET;
var builder = WebApplication.CreateBuilder(args);
await builder.Services.ConfigureQuartzScheduler();
await builder.Services.ConfigureQuartzScheduler();
Let’s see how our scheduler code looks like :
using Quartz.Impl;
namespace Quartz.NET
{
public static class QuartzScheduler
{
public async static Task<IServiceCollection> ConfigureQuartzScheduler(this IServiceCollection services)
{
// Create the Job
var newsletterJob = JobBuilder.Create<NewsletterJob>().Build();
// Add a Trigger for the Job
var trigger = TriggerBuilder.Create()
.WithSimpleSchedule(o => o.RepeatForever().WithIntervalInSeconds(1))
.Build();
// Configure Scheduler and Use SQL
services.AddQuartz(opt =>
{
opt.UsePersistentStore(s =>
{
s.UseSqlServer("Connection String");
s.UseJsonSerializer();
});
});
services.AddQuartzHostedService(opt =>
{
opt.WaitForJobsToComplete = true;
});
// Using Schedule Factory to Schedule Jobs
var factory = new StdSchedulerFactory();
IScheduler scheduler = await factory.GetScheduler();
await scheduler.ScheduleJob(newsletterJob, trigger);
// If we aren't using the Microsoft Hosting framework, explicitly start the scheduler
await scheduler.Start();
return services;
}
}
}
Key points :
-
If we want to use our own storage then we can configure SQL otherwise it will automatically use our RAM Job Store.
-
Using With Identity to group jobs while creating the jobs and triggering them.
-
Where I have used WithSimpleSchedule you can use Calendar/CRON as per your need’s
After running the application that’s how our console looks like :
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place