Quartz.NET Scheduled Jobs
Define jobs and triggers with Quartz.NET, use cron expressions, and integrate with ASP.NET Core DI.
Quartz.NET Scheduled Jobs is a free C# Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Quartz.NET?
When you need cron expressions, job persistence, clustering, retry policies, and job chains — Quartz.NET provides a production-grade scheduler beyond what PeriodicTimer offers. It's the .NET port of the popular Java Quartz scheduler.
Installing Quartz.NET
Add the Quartz and Quartz.AspNetCore packages. The ASP.NET integration automatically registers the scheduler as a hosted service.
# Install packages
dotnet add package Quartz
dotnet add package Quartz.AspNetCore
# Optional: persistence (requires Quartz.Serialization.Json too)
# dotnet add package Quartz.Jobs
# dotnet add package Quartz.PluginsDefining a Job
Implement IJob (or IAsyncJob in newer Quartz) with an Execute method. The job context provides runtime data and the current trigger info.
using Quartz;
[DisallowConcurrentExecution] // prevent overlapping executions
public class ReportGeneratorJob : IJob
{
private readonly IReportService _reports;
private readonly ILogger<ReportGeneratorJob> _logger;
public ReportGeneratorJob(IReportService r, ILogger<ReportGeneratorJob> l)
{ _reports = r; _logger = l; }
public async Task Execute(IJobExecutionContext context)
{
_logger.LogInformation("Generating report at {Time}", DateTime.UtcNow);
await _reports.GenerateDailyReportAsync(context.CancellationToken);
_logger.LogInformation("Report generated");
}
}Registering Quartz in ASP.NET Core
Use AddQuartz to configure the scheduler and AddQuartzHostedService to run it as an IHostedService. Jobs and triggers are configured in the lambda.
builder.Services.AddQuartz(q =>
{
q.UseMicrosoftDependencyInjectionJobFactory();
var jobKey = new JobKey("ReportGenerator");
q.AddJob<ReportGeneratorJob>(opts => opts.WithIdentity(jobKey));
q.AddTrigger(opts => opts
.ForJob(jobKey)
.WithIdentity("ReportTrigger")
.WithCronSchedule("0 0 8 * * ?") // 8:00 AM daily
);
});
builder.Services.AddQuartzHostedService(q =>
q.WaitForJobsToComplete = true);Cron Expression Syntax
Quartz uses a 6 or 7-field cron expression: seconds minutes hours day-of-month month day-of-week [year]. Quartz cron is slightly different from Unix cron — seconds are first.
// Quartz cron format: sec min hour dom month dow [year]
"0 0 8 * * ?" // Every day at 8:00 AM
"0 0/30 9-17 * * ?" // Every 30 min, 9 AM - 5 PM weekdays
"0 0 0 1 * ?" // First day of every month at midnight
"0 0 6 ? * MON-FRI" // Every weekday at 6 AM
"0 0/5 * * * ?" // Every 5 minutes
// Tip: use cronmaker.com or crontab.guru to build expressionsSimple Triggers
For interval-based schedules without cron complexity, use simple triggers with WithSimpleSchedule.
q.AddTrigger(opts => opts
.ForJob(jobKey)
.WithIdentity("CleanupTrigger")
.StartNow()
.WithSimpleSchedule(s => s
.WithIntervalInHours(1)
.RepeatForever())
);
// Or a one-shot trigger:
q.AddTrigger(opts => opts
.ForJob(jobKey)
.WithIdentity("OneShot")
.StartAt(DateTimeOffset.UtcNow.AddMinutes(5)));Job Data Map
Pass runtime parameters to jobs via the JobDataMap. Access them inside Execute through context.JobDetail.JobDataMap.
q.AddJob<EmailJob>(opts => opts
.WithIdentity("EmailJob")
.UsingJobData("to", "admin@example.com")
.UsingJobData("subject", "Daily Digest"));
// Inside the job:
public async Task Execute(IJobExecutionContext context)
{
var to = context.JobDetail.JobDataMap.GetString("to");
var subject = context.JobDetail.JobDataMap.GetString("subject");
await _mailer.SendAsync(to!, subject!, "body");
}DisallowConcurrentExecution
[DisallowConcurrentExecution] prevents a new instance of the job from starting while a previous one is still running. Essential for jobs that access shared resources.
[DisallowConcurrentExecution]
public class InventorySyncJob : IJob
{
// If a sync takes > 1 minute and triggers every minute,
// the next trigger is delayed until this one completes
public async Task Execute(IJobExecutionContext context)
{
await SyncInventoryAsync(context.CancellationToken);
}
}
// Without [DisallowConcurrentExecution], multiple instances
// could run in parallel, causing data conflicts.Exception Handling and Retry
Wrap job code in try/catch. Throw JobExecutionException to signal Quartz to refire the job immediately or after a delay.
public async Task Execute(IJobExecutionContext context)
{
try
{
await ProcessAsync(context.CancellationToken);
}
catch (TransientException ex)
{
// Ask Quartz to retry immediately
var jobException = new JobExecutionException(ex)
{
RefireImmediately = true
};
throw jobException;
}
catch (Exception ex)
{
_logger.LogError(ex, "Job failed — not retrying");
// Don't rethrow — job is done
}
}Real-World: Multi-Job Scheduler
A production Quartz setup with multiple jobs at different schedules, all using DI for services.
builder.Services.AddQuartz(q =>
{
q.UseMicrosoftDependencyInjectionJobFactory();
// Daily report at 8 AM
var reportKey = new JobKey("DailyReport");
q.AddJob<ReportGeneratorJob>(o => o.WithIdentity(reportKey));
q.AddTrigger(o => o.ForJob(reportKey)
.WithCronSchedule("0 0 8 * * ?"));
// Inventory sync every 15 minutes
var syncKey = new JobKey("InventorySync");
q.AddJob<InventorySyncJob>(o => o.WithIdentity(syncKey));
q.AddTrigger(o => o.ForJob(syncKey)
.WithSimpleSchedule(s => s
.WithIntervalInMinutes(15)
.RepeatForever()));
// Cache cleanup every night at 2 AM
var cacheKey = new JobKey("CacheCleanup");
q.AddJob<CacheCleanupJob>(o => o.WithIdentity(cacheKey));
q.AddTrigger(o => o.ForJob(cacheKey)
.WithCronSchedule("0 0 2 * * ?"));
});Quick Check
What does the [DisallowConcurrentExecution] attribute do on a Quartz.NET job?
Recap: Quartz.NET Scheduled Jobs
Key takeaways:
- Quartz.NET: production-grade scheduler with cron, persistence, and clustering
- Define jobs by implementing IJob with an Execute method
- Register with AddQuartz + AddQuartzHostedService; jobs are DI-aware
- Cron format: seconds minutes hours dom month dow — note seconds-first
[DisallowConcurrentExecution]: wait for current execution to finish before re-firing- Use JobDataMap to pass runtime parameters to jobs
Frequently asked questions
Is the “Quartz.NET Scheduled Jobs” lesson free?
Yes — the full text of “Quartz.NET Scheduled Jobs” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “Quartz.NET Scheduled Jobs”?
Define jobs and triggers with Quartz.NET, use cron expressions, and integrate with ASP.NET Core DI. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Quartz.NET Scheduled Jobs” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- IHostedService & BackgroundService
- Worker Service Projects
- Periodic Tasks & Timers
- Quartz.NET Scheduled Jobs