Implementing Scheduled Jobs in .NET Core with Quartz.NET

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

  1. Generate a new console application:

    dotnet new console -n SchedulerApp
    cd SchedulerApp
    
  2. Install the Quartz library via NuGet:

    dotnet add package Quartz --version 3.3.3
    
  3. Update Program.cs with the following implementation. This defines a job named TimeLoggerTask that 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();
            }
        }
    }
    
  4. 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.

Tags: dotnet core quartz.net scheduling csharp background tasks

Posted on Sun, 05 Jul 2026 16:42:45 +0000 by Neoraven456