top of page

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

using Quartz;
using Quartz.Impl;
using System;
using System.Threading.Tasks;
namespace QuartzSample
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // 1. Create a scheduler Factory
            ISchedulerFactory schedulerFactory = new StdSchedulerFactory();            // 2. Get and start a scheduler
            IScheduler scheduler = await schedulerFactory.GetScheduler();
            await scheduler.Start();            // 3. Create a job
            IJobDetail job = JobBuilder.Create<NumberGeneratorJob>()
                    .WithIdentity("number generator job", "number generator group")
                    .Build();            // 4. Create a trigger
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("number generator trigger", "number generator group")
                .WithSimpleSchedule(x => x.WithIntervalInSeconds(15).RepeatForever())
                .Build();            // 5. Schedule the job using the job and trigger 
            await scheduler.ScheduleJob(job, trigger);            Console.ReadLine();
        }
    }
}

At this point, we have a console app that has a background job which generates a random number every 15 secs. This is the very basic use of background jobs, but the same principle works for more complicated situations. I found myself more challenged when I needed to have dependencies injected into the job class . There are more setup details that can be talked about, and I might write another post about those specifics.



Source: Medium - MBARK T3STO


The Tech Platform

0 comments

Comments


bottom of page