Create a background job with Quartz.Net in .NET Core

There are processes you want to run frequently and automatically in the background of your main application. There are many libraries dedicated to this problem, and Quartz.Net is one of the known ones out there.


In this post, I’m going to create a .NET Core console app that will generate a random number on the console output, every 15 seconds.


The first step will be installing the latest stable Quartz NuGet package on your project


Create the Job Class

I’m going to create a job that will generate a 4 digit random number and print it on the console. The class needs to implement IJob interface which lives in Quartz namespace


NumberGeneratorJob.cs

using Quartz;
using System;
using System.Threading.Tasks;

namespace QuartzSample
{
    public class NumberGeneratorJob : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {
            Console.WriteLine($"Your # is:                   {RandomNumber(1000,9999)}");
            await Task.CompletedTask;
        }

        private int RandomNumber(int min, int max)
        {
            var random = new Random();
            return random.Next(min, max);
        }
    }
}


Quartz.Net Setup and Job Schedule

After creating the job class, we are going to code the rest of this example in the Main method of Program.cs file. Since we are going to call async methods and await them inside the Main. I will convert the Main to an async method.


There are 5 small steps that you need to consider to make this code work.

  1. Create a scheduler Factory

  2. Get and start a scheduler

  3. Create a job

  4. Create a trigger

  5. Schedule the job