π QuartzHostedService Documentation
π Table of Contents
- Overview & Purpose
- Key Functional Areas
- Dependencies & Technologies
- Code Walkthrough
4.1 Constructor & DI
4.2 StartAsync Method
4.3 StopAsync Method
4.4 CreateJob & CreateTrigger Helpers - Usage Example
5.1 Define a Job
5.2 Register Services inProgram.cs/Startup.cs
5.3 Run the Application - UML Class Diagram
- Error Handling & Return Types
- Conclusion
π§ Overview & Purpose
QuartzHostedService is an integration layer between the Quartz.NET scheduling library and the .NET Generic Host (IHostedService). Its main responsibilities are:
- Bootstrapping a Quartz scheduler instance on application start.
- Registering a set of jobs with their associated cron triggers.
- Gracefully shutting down the scheduler on application stop.
Use Case: Run recurring background tasks (e.g., file cleanup, email notifications, report generation) in an ASP.NET Core or generic host application.
βοΈ Key Functional Areas
| Area | Description |
|---|---|
| Dependency Injection | Receives ISchedulerFactory, IJobFactory & job schedules via constructor |
| Scheduler Lifecycle Control | Implements StartAsync and StopAsync to manage scheduler state |
| Job & Trigger Creation | Builds IJobDetail and ITrigger objects from custom JobSchedule data |
| Job Scheduling | Iterates through all configured schedules and registers them with Quartz |
π Dependencies & Technologies
- .NET Generic Host (
Microsoft.Extensions.Hosting) - Quartz.NET
Quartz ISchedulerFactory,IJobFactory,IJobDetail,ITrigger, etc.
- Language: C# 9.0+ (async/await, DI)
π Code Walkthrough
namespace IrbyImaging.BusinessLogic.Scheduler
{
public class QuartzHostedService : IHostedService
{
private readonly ISchedulerFactory _schedulerFactory;
private readonly IJobFactory _jobFactory;
private readonly IEnumerable<JobSchedule> _jobSchedules;
public IScheduler Scheduler { get; set; }
public QuartzHostedService(
ISchedulerFactory schedulerFactory,
IJobFactory jobFactory,
IEnumerable<JobSchedule> jobSchedules)
{
_schedulerFactory = schedulerFactory;
_jobFactory = jobFactory;
_jobSchedules = jobSchedules;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
// 1. Create or retrieve the scheduler
Scheduler = await _schedulerFactory.GetScheduler(cancellationToken);
Scheduler.JobFactory = _jobFactory;
// 2. Register each job and its trigger
foreach (var schedule in _jobSchedules)
{
var job = CreateJob(schedule);
var trigger = CreateTrigger(schedule);
await Scheduler.ScheduleJob(job, trigger, cancellationToken);
}
// 3. Start processing jobs
await Scheduler.Start(cancellationToken);
}
public async Task StopAsync(CancellationToken cancellationToken)
=> await Scheduler?.Shutdown(cancellationToken);
private static IJobDetail CreateJob(JobSchedule schedule)
=> JobBuilder.Create(schedule.JobType)
.WithIdentity(schedule.JobType.FullName)
.WithDescription(schedule.JobType.Name)
.Build();
private static ITrigger CreateTrigger(JobSchedule schedule)
=> TriggerBuilder.Create()
.WithIdentity($"{schedule.JobType.FullName}.trigger")
.WithCronSchedule(schedule.CronExpression)
.WithDescription(schedule.CronExpression)
.Build();
}
}
4.1 Constructor & DI
- Parameters
Parameter Role ISchedulerFactoryFactory to create or retrieve a Quartz scheduler instance IJobFactoryAllows DI container to resolve job dependencies at runtime IEnumerable<JobSchedule>Collection of custom schedules (job type + cron expression)
QuartzHostedService is registered as a hosted service. The DI container provides all dependencies.
4.2 StartAsync Method
- Get Scheduler
Scheduler = await _schedulerFactory.GetScheduler(cancellationToken); - Assign JobFactory
Enables constructor injection for jobs - Iterate Schedules
- Create a job detail via
CreateJob(schedule) - Create the cron trigger via
CreateTrigger(schedule) - Register both with
ScheduleJob(...)
- Create a job detail via
- Start Scheduler
Begins processing according to triggers
4.3 StopAsync Method
- Calls
Scheduler.Shutdown(...)to gracefully stop all executing jobs. - Honours
cancellationTokento abort if needed.
4.4 CreateJob & CreateTrigger Helpers
| Method | Input | Output | Purpose |
|---|---|---|---|
CreateJob |
JobSchedule |
IJobDetail |
Wraps job type in Quartzβs detail object |
CreateTrigger |
JobSchedule |
ITrigger |
Defines a cron-based trigger for the job |
JobSchedule is a simple model:
public class JobSchedule
{
public Type JobType { get; }
public string CronExpression { get; }
public JobSchedule(Type jobType, string cronExpression)
{
JobType = jobType;
CronExpression = cronExpression;
}
}
π οΈ Usage Example
5.1 Define a Job
public class CleanupJob : IJob
{
public Task Execute(IJobExecutionContext context)
{
// Your cleanup logic here
Console.WriteLine("Performing cleanup at " + DateTime.Now);
return Task.CompletedTask;
}
}
5.2 Register Services in Program.cs / Startup.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
// Quartz services
services.AddSingleton<IJobFactory, SingletonJobFactory>();
services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
// Register your job and its schedule
services.AddSingleton(new JobSchedule(
jobType: typeof(CleanupJob),
cronExpression: "0 0 * ? * * *" // every hour
));
// Hosted service wrapper
services.AddHostedService<QuartzHostedService>();
});
5.3 Run the Application
dotnet run
You should see the scheduler start and your job executing as per the cron expression.
π UML Class Diagram
@startuml
class QuartzHostedService {
- ISchedulerFactory _schedulerFactory
- IJobFactory _jobFactory
- IEnumerable<JobSchedule> _jobSchedules
+ IScheduler Scheduler
+ StartAsync(CancellationToken): Task
+ StopAsync(CancellationToken): Task
- CreateJob(JobSchedule): IJobDetail
- CreateTrigger(JobSchedule): ITrigger
}
class JobSchedule {
- Type JobType
- string CronExpression
+ JobSchedule(Type, string)
}
QuartzHostedService --> ISchedulerFactory
QuartzHostedService --> IJobFactory
QuartzHostedService o-- JobSchedule
QuartzHostedService ..> IScheduler
QuartzHostedService ..> ITrigger
QuartzHostedService ..> IJobDetail
@enduml
Render with PlantUML or any UML viewer.
π¨ Error Handling & Return Types
- Return Types
StartAsync&StopAsyncreturnTaskto integrate with the .NET Generic Host.
- Error Handling
- Exceptions during job scheduling or start will bubble up to the host, resulting in a crash if unhandled.
- You can wrap scheduling logic in
try/catchor use Quartzβs built-in job misfire policies if desired.
β Conclusion
QuartzHostedService simplifies the hosting of Quartz jobs in a .NET Core application by:
- Managing scheduler lifecycle automatically.
- Centralizing job registration and trigger configuration.
- Enabling full DI support for your Quartz jobs.
π Next Steps:
- Define additional jobs and schedules.
- Explore advanced Quartz features (listeners, calendars, misfire instructions).
- Monitor and log job execution for production readiness.
Generated by IrbyImaging.BusinessLogic Scheduler Module ππ