Scheduled Tasks In ASP.NET With Quartz.Net

A perennial question on the ASP.NET forums concerns how to schedule regular tasks as part of a web application. Typically, the requirement is to send emails once every 24 hours at a particular time each day, but it could actually be anything from tweeting on a schedule to performing maintenance tasks. Equally typically, half a dozen members on the forum dive in with recommendations to install Windows Services or schedule batch files with the Task Scheduler - regardless of the fact that most web site owners are not afforded such privileges as part of their shared hosting plan.

I've looked at how you can use the Session_Start event in Global.asax to manage rudimentary "timed" jobs previously. However, it relies on there being sufficient traffic to your web site that the event gets fired often enough for your scheduling needs. And of course, if that is not the case, it is of no use when dealing with time-critical tasks. A much more robust solution can be found in the shape of Quartz.NET - an open source scheduling library which is available via nuget. This article looks at a basic implementation that will get you up and running with a scheduled email job. I have chosen to use a Web Forms application to illustrate the use of Quartz.NET in an ASP.NET setting, but the steps are easily translated to MVC or Web Pages.

The easiest way to include Quartz.NET in your application is via Nuget. You can do this either by typing Install-Package Quartz at the Package Manager Console prompt or by right clicking on the project in Visual Studio's Solution Explorer and selecting Manage Nuget Packages.

Quartz

Note: If using WebMatrix (ditch it!), just click on the Nuget button in the ribbon bar and ignore the error messages

Then search for 'quartz' and click Install when you find Quartz.NET.

Quartz

At its simplest, Quartz consists of 3 primary components - a job, a trigger and a scheduler. A job is the task to be performed. The trigger dictates how and when the job is executed. Together, the job and the trigger are registered with the scheduler, which takes care of ensuring that the job is performed on the schedule dictated by the trigger configuration.

A job is a class. For it to work with Quartz, it must implement the Quartz IJob interface which has one member: the Execute method. This method defines the actions to be performed. Here's an example of a job:

using Quartz;
using System;
using System.Net;
using System.Net.Mail;

namespace ScheduledTaskExample.ScheduledTasks
{
    public class EmailJob : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            using (var message = new MailMessage("[email protected]", "[email protected]"))
            {
                message.Subject = "Test";
                message.Body = "Test at " + DateTime.Now;
                using (SmtpClient client = new SmtpClient
                {
                    EnableSsl = true,
                    Host = "smtp.gmail.com",
                    Port = 587,
                    Credentials = new NetworkCredential("[email protected]", "password")
                })
                {
                    client.Send(message);
                }
            }
        }
    }
}

The Execute method takes an IJobExecutionContext object as a parameter. The scheduler passes that in when calling the job's Execute method. It contains configuration data about the job (which you set a bit later). In this simple example, no use is made of the data in the context. All this example does in fact is to send an email message. The method body could contain anything that you want to happen. It could query a database and send emails to all the recipients found there, for instance. But on its own, the job does nothing.

The next section of code illustrates the scheduler being set up and the job, together with its trigger being created and assigned:

using Quartz;
using Quartz.Impl;
using System;

namespace ScheduledTaskExample.ScheduledTasks
{
    public class JobScheduler
    {
        public static void Start()
        {
            IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
            scheduler.Start();

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

            ITrigger trigger = TriggerBuilder.Create()
                .WithDailyTimeIntervalSchedule
                  (s =>
                     s.WithIntervalInHours(24)
                    .OnEveryDay()
                    .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(0, 0))
                  )
                .Build();

            scheduler.ScheduleJob(job, trigger);
        }
    }
}

I've called the class in which this takes place JobScheduler, but it could be called anything. In fact, this code doesn't even need to be in its own class. It can be placed wherever you want to start the scheduler. Typically in a web application, that will be in the Application_Start event of Global.asax. In this example, the actual code has been placed in a method called Start (although that too can be named anything). A scheduler is created and started in the first two lines. Then a job is created using the Quartz.NET JobBuilder.Create<T> method, where T is the type of job to be created. In this case, it's an instance of the EmailJob previously defined.

Next, a trigger is created. As I mentioned earlier, the trigger defines when the job is to be executed. In this case, the schedule is specifed as starting daily at midnight and having an interval of 24 hours. It is to execute every day. The options for trigger schedules are extremely flexible allowing for scheduling to a calendar as well as regular time-based intervals. Here's another example of a trigger taken from the documentation:

ITrigger trigger = TriggerBuilder.Create()
    .WithIdentity("trigger1", "group1")
    .StartNow()
    .WithSimpleSchedule(x => x
        .WithIntervalInSeconds(10)
        .RepeatForever())
    .Build();

This trigger has been given a name and group so that it can more easily be identified if you need to refer to it programmatically. It is designated to start immediately an to fire every 10 seconds until the end of time (or the scheduler stops for some reason). The fluent API makes it pretty simple to create triggers and to understand what they are doing.

Finally, the job together with its trigger is registered with the scheduler. All that's needed now is to get this code to execute. As mentioned previously, the best place to do this is within the Application_Start event of the Global.asax file, so a call to the JobScheduler.Start method is added their alongside the other bootstrapping tasks that need to take place on application startup:

using ScheduledTaskExample.ScheduledTasks;
using System;
using System.Web;
using System.Web.Optimization;
using System.Web.Routing;

namespace ScheduledTaskExample
{
    public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            JobScheduler.Start();
        }
    }
}

If you need to run tasks on a schedule as part of your ASP.NET application with reliable accuracy and don't have access to various scheduling options directly on the server - or even want an alternative to messing around with the Windows task scheduler - Quartz.NET is a great solution.