This example demonstrates how to configure a recurring background task in a .NET Core environment using the Quartz.NET library.
Prerequisites
Ensure the .NET Core SDK is installed on your machine.
Setup Instructions
-
Generate a new console application:
dotnet new console -n SchedulerApp cd SchedulerApp -
Install the Quartz library via NuGet:
dotnet add package Quartz --version 3.3.3 -
Update
Program.cswith the following implementation. This defines a job namedTimeLoggerTaskthat triggers every 5 seconds.using System; using System.Threading.Tasks; using Quartz; using Quartz.Impl; namespace SchedulerApp { // Custom job implementation public class TimeLoggerTask : IJob { public Task Execute(IJobExecutionContext context) { Console.WriteLine($"Current timestamp: {DateTime.Now:HH:mm:ss}"); return Task.CompletedTask; } } class Program { static async Task Main(string[] args) { // Initialize the scheduler factory var schedulerFactory = new StdSchedulerFactory(); var schedulerInstance = await schedulerFactory.GetScheduler(); // Begin the scheduling process await schedulerInstance.Start(); // Define the job details var jobDetail = JobBuilder.Create<TimeLoggerTask>() .WithIdentity("logTimeJob", "systemGroup") .Build(); // Configure the trigger to run immediately and repeat var jobTrigger = TriggerBuilder.Create() .WithIdentity("timeTrigger", "systemGroup") .StartNow() .WithSimpleSchedule(schedule => schedule .WithIntervalInSeconds(5) .RepeatForever()) .Build(); // Associate job and trigger await schedulerInstance.ScheduleJob(jobDetail, jobTrigger); Console.WriteLine("Scheduler is running. Press any key to stop..."); Console.ReadKey(); // Gracefully stop the scheduler await schedulerInstance.Shutdown(); } } } -
Execute the application:
dotnet run
The console will display the current time every 5 seconds. You can modify the TimeLoggerTask logic or adjust the WithIntervalInSeconds value to change the execution frequency or behavoir.