Getting Started with Quartz.NET for Periodic Tasks
To implement periodic tasks in C#, you first need to reference the Quartz NuGet package in your project.
Next, define a scheduler initialization class that manages three core components: the scheduler itself, the job detail (specifying what to execute), and the trigger (defining when and how often too run).
public static async Task InitializeScheduler()
{
// Initialize scheduler instance
var schedulerFactory = new StdSchedulerFactory();
var scheduler = await schedulerFactory.GetScheduler();
await scheduler.Start();
// Create job definition
var dailyAlertJob = JobBuilder.Create<DailyAlertTask>()
.WithIdentity("dailyHealthCheck", "notificationGroup")
.WithDescription("System health check job running at regular intervals")
.Build();
// Configure execution trigger
var intervalTrigger = TriggerBuilder.Create()
.WithIdentity("dailyHealthCheckTrigger", "notificationGroup")
// Uncomment to run immediately on startup
//.StartNow()
.WithSimpleSchedule(config => config
.WithIntervalInSeconds(5)
.WithRepeatCount(3)) // Runs 4 times total (initial + 3 repeats); use RepeatForever() for endless execution
.Build();
// Associate job and trigger with the scheduler
await scheduler.ScheduleJob(dailyAlertJob, intervalTrigger);
}
The DailyAlertTask class is your custom implementation of the periodic behavior, inehriting from Quartz's IJob interface.
public class DailyAlertTask : IJob
{
public async Task Execute(IJobExecutionContext context)
{
await Task.Run(() =>
{
Console.WriteLine("=========================================");
Console.WriteLine($"Daily system health check executed at {DateTime.Now}");
Console.WriteLine("=========================================");
Console.WriteLine();
});
}
}
To start the scheduler and begin executing tasks, call the initialization method from your application entry point.
SchedulerBootstrap.InitializeScheduler().GetAwaiter().GetResult();