Introduction
Quartz.NET is an open-source job scheduling library for .NET applications, enabling developers to execute background tasks at specified times or intervals. This article explains what is quartz, it’s applications and use cases. Additionally, it will demonstrate how to implement it in a .NET application with an example and code sample.
What is Quartz.NET?
Quartz.NET is an open-source job scheduling library for .NET applications. It provides a robust, feature-rich, and scalable scheduling solution that enables developers to execute background tasks at specific times or intervals. Quartz.NET is a port of the Java-based Quartz Scheduler and is widely used in enterprise applications to handle scheduled jobs efficiently.
Why Use Quartz.NET?
In many software applications, there is a need to execute tasks at scheduled times, such as:
- Running background maintenance tasks (e.g., cleaning logs, updating records, generating reports)
- Sending scheduled notifications (emails, push notifications, SMS reminders)
- Processing queued jobs asynchronously
- Automating workflows and batch processing
Quartz.NET helps to achieve these functionalities with its flexible scheduling capabilities, making it an essential tool for developers.
Key Features of Quartz.NET
Quartz.NET provides several powerful features for developers for examples:
- Flexible Scheduling: Supports simple intervals (e.g., every 10 minutes) and complex Cron-like expressions.
- Persistent Jobs: Jobs can be stored in a database for reliability and resilience.
- Clustered Execution: Supports job execution across multiple servers to ensure high availability.
- Dependency Injection Support: Works seamlessly with .NET Core dependency injection.
- Scalability: Can handle thousands of scheduled jobs with high performance.
- Transactional Support: Ensures that jobs are executed reliably within a transactional context.
- Multiple Job Types: Supports one-time jobs, recurring jobs, and jobs triggered by events.
Common use cases of Quartz.NET
1. Automated Report Generation
Many businesses require periodic reports (e.g., daily sales reports and system health reports). Quartz.NET can schedule jobs to generate and send these reports automatically.
2. Email and Notification Scheduling
Applications often send reminders, promotional emails, or system alerts at specific times. With Quartz.NET, you can schedule and manage email campaigns efficiently.
3. Database Maintenance Tasks
Background jobs like data cleanup, indexing, or archiving old records can be scheduled using Quartz.NET, ensuring the database remains optimized.
4. Batch Processing and Data Synchronization
Enterprise applications often require data synchronization between different systems. Quartz.NET can execute these tasks at defined intervals to maintain data consistency.
5. Automating Business Processes
Businesses use workflows for tasks like invoice generation, order processing, and billing cycles. Quartz.NET allows developers to schedule these processes efficiently.
How Quartz.NET Works?
Quartz.NET operates based on three core components:
- Jobs: Define the task to be executed.
- Triggers: Determine when the job should run (e.g., every hour, once a day, specific dates).
- Schedulers: Manage and execute jobs based on their triggers.
Now, let’s move for implementation of Quartz.NET.
Implementing Quartz.NET in ASP.NET core web API
Step 1. Create ASP.NET Core Web API project using Visual Studio or VS code.
Step 2. Install the following packages for Quartz.NET
Install-Package Quartz
If you need JSON Serialization, just add the either Quartz.Serialization.SystemTextJson
or Quartz.Serialization.Json
package the same way.
Step 3. Code implementation
In Program.cs add the following line to register Quartz.NET as a hosted service.
// Add Quartz.NET as a hosted service
builder.Services.AddQuartzHostedService(options =>
{
options.WaitForJobsToComplete = true;
});
Step 4– We will create Interface and service for Quartz Scheduler as follows:
public interface IQuartzJobScheduler
{
Task ScheduleJobAsync<TJob>(TimeSpan delay, string userId, string message, CancellationToken cancellationToken) where TJob : IJob;
}
public class QuartzJobScheduler(ISchedulerFactory schedulerFactory, ILogger<QuartzJobScheduler> logger) : IQuartzJobScheduler
{
private readonly ISchedulerFactory _schedulerFactory = schedulerFactory;
private IScheduler? _scheduler;
private readonly ILogger<QuartzJobScheduler> _logger = logger;
public async Task StartAsync(CancellationToken cancellationToken)
{
_scheduler = await _schedulerFactory.GetScheduler(cancellationToken);
await _scheduler.Start(cancellationToken);
}
public async Task ScheduleJobAsync<TJob>(TimeSpan delay, string userId, string message, CancellationToken cancellationToken) where TJob : IJob
{
_logger.LogInformation("Scheduling job {JobName} for user {UserId} with message {Message}", typeof(TJob).Name, userId, message);
var jobDetail = JobBuilder.Create<TJob>()
.WithIdentity($"{typeof(TJob).Name}-{userId}")
.UsingJobData("userId", userId)
.UsingJobData("message", message)
.Build();
var scheduler = await _schedulerFactory.GetScheduler();
var trigger = TriggerBuilder.Create()
.StartAt(DateTimeOffset.Now.Add(delay))
.Build();
await scheduler.ScheduleJob(jobDetail, trigger, cancellationToken);
}
}
Then, we will register Dependency in the services in Program.cs, as shown below.
//add dependency injection for QuartzJobScheduler
builder.Services.AddSingleton<IQuartzJobScheduler, QuartzJobScheduler>();
Here is a sample controller for the Schedular.
using Microsoft.AspNetCore.Mvc;
using QuartzSceduleSample.Jobs;
namespace QuartzSceduleSample.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TestSceduleController : ControllerBase
{
private readonly IQuartzJobScheduler _quartzJobScheduler;
public TestSceduleController(IQuartzJobScheduler quartzJobScheduler)
{
_quartzJobScheduler = quartzJobScheduler;
}
[HttpPost]
public async Task<IActionResult> PostAsync(CancellationToken cancellationToken)
{
//create a new job sample job
await _quartzJobScheduler.ScheduleJobAsync<EmailReminderJob>(TimeSpan.FromSeconds(10), "123", "Hello World", cancellationToken);
return Ok("Job is scheduled");
}
}
}
In the above code, we schedule the job after 10 seconds.
Project structure
![]()
Let’s call the API and check the output of the controller is given below.
![Result]()
We will see the job will be executed after 10 seconds.
Here is the repository with the complete code, Click here.
Conclusion
Quartz.NET is a powerful and flexible job scheduling library that seamlessly integrates with ASP.NET Core. It enables developers to automate background tasks, schedule recurring jobs, and manage workflows efficiently. By implementing Quartz.NET, you can improve application performance, optimize resource utilization, and ensure timely execution of critical tasks. Whether you’re handling database cleanups, email notifications, or report generation, Quartz.NET provides a reliable solution for job scheduling in ASP.NET Core applications.
Reference