joydip_kanjilal
Contributor

How to work with Quartz.Net in C#

opinion
Jun 03, 20164 mins
Software Development

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

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.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author