How to work with Quartz.Net in C#

The Quartz.Net open source framework schedules, controls, and manages your recurring tasks

Quartz.net

Quartz.net

When working on applications, you'll often need to execute certain tasks in the background in predefined intervals of time. Scheduling jobs in applications is a challenge, and you can choose from many available frameworks around, such as Quartz, Hangfire, etc.

Quartz.Net has been in use for a long time and provides better support for working with Cron expressions. Hangfire is yet another job scheduler framework that takes advantage of the request processing pipeline of ASP.Net for processing and executing jobs.

Quartz.Net is a .Net port of the popular Java job scheduling framework. It's an open source job scheduling system that can be used from smallest apps to large-scale enterprise systems. The official website of Quartz.Net states: "Quartz.Net is a full-featured, open source job scheduling system that can be used from smallest apps to large scale enterprise systems."

Getting started

You can install Quartz.Net from the downloads section of the Quartz official website. You can also install Quartz.Net through the Package Manager Window in your Visual Studio IDE.

The three primary components in Quartz are jobs, triggers and schedulers, i.e., to create and schedule jobs in Quartz.Net, you would need to have schedulers, triggers and jobs. While a job denotes the task that needs to be executed, a trigger is used to specify how the job will be executed. The scheduler is the component that schedules the jobs. Note that you should register your jobs and triggers with the scheduler.

Programming Quartz.Net in C#

To create a job, you should create a class that implements the IJob interface. Incidentally, this interface declares the Execute method -- you should implement this method in your custom job class. The following code snippet illustrates how you can implement the IJob interface to design a custom job class using the Quartz.Net library.

public class IDGJob : IJob

   {

       public void Execute(IJobExecutionContext context)

       {

           //Sample code that denotes the job to be performed

       }

   }

Here's a simple implementation of the Execute method of the IDGJob class -- I'll leave it to you to design your custom job class to suit your application's needs. The code snippet given below writes the current DateTime value as a text to a file. Note that this implementation is not thread safe; it's just for illustration purposes only.
public void Execute(IJobExecutionContext context)
        {
            using (StreamWriter streamWriter = new StreamWriter(@"D:\IDGLog.txt", true))
            {
                streamWriter.WriteLine(DateTime.Now.ToString());
            }
        }

Now that you have already defined the job class, you'll need to create your own job scheduler class and define the trigger for your job. The trigger will contain the job's metadata as cron expression. You can visit this link to generate cron expressions.

Now, how is that the jobs are scheduled? Well, there is a component called job scheduler that is responsible for scheduling your jobs. In essence, you can take advantage of job schedulers to schedule your jobs for execution. The following code listing illustrates how we can define a trigger for our job and then register job and the trigger with the job scheduler.

public class JobScheduler

   {

       public static void Start()

       {

           IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();

           scheduler.Start();

           IJobDetail job = JobBuilder.Create<IDGJob>().Build();

           ITrigger trigger = TriggerBuilder.Create()

               .WithIdentity("IDGJob", "IDG")

               .WithCronSchedule("0 0/1 * 1/1 * ? *")

               .StartAt(DateTime.UtcNow)

               .WithPriority(1)

               .Build();

              scheduler.ScheduleJob(job, trigger);

       }

   }

Refer to the code listing given above. Note how the name and group of the trigger has been specified when creating the trigger instance. Once the trigger for the job is defined and configured using the needed cron expression, the trigger is registered with the job scheduler.

You can as well build a trigger that is fired every second and repeats it indefinitely. Here's a code snippet that illustrates how you can build a trigger like this.

ITrigger trigger = TriggerBuilder.Create()

 .WithIdentity("IDGJob", "IDG")

   .StartNow()

   .WithSimpleSchedule(s => s

       .WithIntervalInSeconds(10)

       .RepeatForever())

   .Build();

You do not always need a windows service to start your scheduler. If you are using an ASP.Net web application, you can take advantage of the Application_Start event of the Global.asax file and then make a call to JobScheduler.Start() method as shown in the code snippet below.

public class Global : HttpApplication

   {

       void Application_Start(object sender, EventArgs e)

       {

           // Code that runs on application startup

           JobScheduler.Start();

       }

   }

Note that JobScheduler is the name of the custom class we designed earlier. Note that you can also leverage Quartz.Net to store your jobs to persistent storages, i.e., you can persist your jobs in database as well. You can know the list of all the supported job stores from here.

This article is published as part of the IDG Contributor Network. Want to Join?

To comment on this article and other InfoWorld content, visit InfoWorld's LinkedIn page, Facebook page and Twitter stream.
From CIO: 8 Free Online Courses to Grow Your Tech Skills
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.