Using Quartz.Net to Create Scheduled Tasks

January 9th, 2012
By: Cory Mathews

These steps are using version 1.0.3, and do not apply to version 2.x

Quartz.Net is a full-featured, open source job scheduling system. Basically this system allows an asp.net web application to schedule and run background jobs. This makes it much simpler for us developers by making it so that we do not have to have a windows service running on the server as well.

To get started open up the NuGet package manager. (right click on the projects name, and select Manage NuGet Packages) Search for Quartz and click install. This will add the needed references as well as download the Common.Logging dependency if needed.

Now to the code, we need to create our Job which will be run by the scheduler. This class must use the IJob interface provided from Quartz.Net.

...
using Quartz;
using Quartz.Impl;
...

public class DailyJob : IJob
{
    public DailyJob() { }

    public void Execute( JobExecutionContext context )
    {
        try {
            //Your Logic
        } catch( Exception e ) {
            //Handle this please
        }
    }

    public static void ScheduleJob( IScheduler sc ) 
    { 
        JobDetail job = new JobDetail( "Send", "Daily", typeof( DailyJob ) );
        sc.ScheduleJob( job, TriggerUtils.MakeDailyTrigger( "trigger1", 8, 15 ) );
        sc.Start();
    }
}

The code placed in the Execute function is obviously what will run when the job is executed at its scheduled time. If you fail to add the try/catch block then the code can silently fail without being caught by a global error handler since there is no http request present. The ScheduleJob function is not required by the IJob interface but seems more logical to me, so it is added as well.

The Scheduling function above creates a new job Daily.Send (thats GroupName.TaskName ) and schedules it to run daily at 8:15am (14, 15 would be 2:15pm). You can replacing the TriggerUtils.MakeDailyTrigger with how often you want the Job to run, such as every 20 minutes, every hour, etc.

Lastly we need to call this Schedule function from the Global.asax Application_Start function so that when our app starts the code is automatically scheduled.

DailyJob.ScheduleJob( new StdSchedulerFactory().GetScheduler() );