Quartz.NET 2 Tutorial - Lesson 1: Using Quartz

Lesson 1: Using Quartz

There are at least two ways to use Quartz.Net: embedded (hosted) in your application or as a standalone windows service.

Embedding Quartz.Net in Your Application

If you are going to host the Quartz.Net scheduler in your application, you’ll need to create a scheduler. This can be easily done through the scheduler factory provided in the distribution. The scheduler factory configures your scheduler for you.

Once you’ve got a reference to the scheduler, and in order to be able to do something useful with it, you must start it. After your scheduler is started it will start firing triggers and executing the jobs that have been loaded. We’ll talk more about how to load jobs into the scheduler later, but one way to do it is to add them every time you start the scheduler.

The example below shows you how to create and start a scheduler. It also adds a job that writes some output to the screen to demonstrate that it is running. You can download the code below and all the samples for the tutorial from github.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Quartz;
using Quartz.Impl;
using Quartz.Job;

namespace Lesson1 { class Program { static void Main(string[] args) { //Create the scheduler factory ISchedulerFactory schedulerFactory = new StdSchedulerFactory();

        //Ask the scheduler factory for a scheduler
        IScheduler scheduler = schedulerFactory.GetScheduler();

        //Start the scheduler so that it can start executing jobs

        // Create a job of Type WriteToConsoleJob
        IJobDetail job = JobBuilder.Create(typeof(WriteToConsoleJob)).WithIdentity("MyJob", "MyJobGroup").Build();

        //Schedule this job to execute every second, a maximum of 10 times
        ITrigger trigger = TriggerBuilder.Create().WithSchedule(SimpleScheduleBuilder.RepeatSecondlyForTotalCount(10)).StartNow().WithIdentity("MyJobTrigger", "MyJobTriggerGroup").Build();
        scheduler.ScheduleJob(job, trigger);

        //Wait for a key press. If we don't wait the program exits and the scheduler gets destroyed

        //A nice way to stop the scheduler, waiting for jobs that are running to finish


Using Quartz.Net as a Standalone Windows Service

To use Quartz.Net as a windows service you’ll need to install and configure it. Installing it is covered in depth in the quick start guide, which you can download here.

Wrapping Up

Setting up a Quartz.Net scheduler is fairly straightforward. We’ve described how to start one up inside your application and also as a windows service. In Lesson 2 we’ll look at Jobs and Triggers.