Using Quartz .net scheduler

Quartz .net scheduler example

Here's a simple example using the Quartz Scheduler within the context of a Canvas Application & Control

What's Quartz.net?

Think of it as the *nix cron / crontab tool for C#. It allows you to schedule jobs that need to be performed at given time or intervals.

In a asp.net app?

Yep, as the canvas application runs 24/7 you can use it's http service as a means to run the scheduler.

A Quick 'n' Dirty Example!

So I declare a static IScheduler that's initial value is null, then everytime the control used it's checked and initialized if it's null.

using System;
using System.Linq;
using System.Threading;
using System.Web.UI.WebControls;
using System.Collections.Generic;

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

using Net4orce.Core.Canvas.Meta;

namespace TestQuartz
{
  public class Test1 : ControlBase, IDesignerControl
  {

    public static List<string> Results = new List<string>();

    public Repeater rpList;

    public static IScheduler scheduler = null;
    public static IJobDetail job = null;

    protected override void initialize()
    {
      base.initialize();
      start();

      render();
    }

    private void render()
    {
      rpList.DataSource = Results;
      rpList.DataBind();
    }

    protected void btnStop_Click(object sender, EventArgs e)
    {
      stop();
    }


    private void start()
    {

      if( scheduler != null ) { return; }

      // Grab the Scheduler instance from the Factory 
      scheduler = StdSchedulerFactory.GetDefaultScheduler();

      // and start it off
      scheduler.Start();

      // define the job and tie it to our HelloJob class
      job = JobBuilder.Create<HelloJob>()
        .Build();

      // Create a Trigger
      var trigger = TriggerBuilder.Create()

        // Every 5 Seconds between 8am & 5pm
        .WithCronSchedule("0/5 * 8-17 * * ?")

        .Build();

      // Tell quartz to schedule the job using our trigger
      scheduler.ScheduleJob(job, trigger);
    }

    private void stop()
    {
      if( scheduler == null ) { return; }

      scheduler.Shutdown();
    }

    public bool Designer { get; set; }

  }


  public class HelloJob : IJob
  {
    public void Execute(IJobExecutionContext context)
    {
      // Add an item to the List 
      Test1.Results.Add(
        DateTime.Now.ToLongTimeString() +  " : Hello World!"
      );
    }
  }
}

Here's the simple ASCX content :

<%@ Control Language="C#" AutoEventWireup="true" Inherits="TestQuartz.Test1" %>
<%@ Import namespace="TestQuartz"%>

<h1>
  Scheduled Results
</h1>

<asp:repeater runat="server" id="rpList">
  <itemtemplate>
    <pre><%# Container.DataItem %></pre>
  </itemtemplate>
</asp:repeater>

Results in something like this :

16:41:36 : Hello World!

Reload 10 seconds later and we see :

16:41:36 : Hello World!

16:41:40 : Hello World!

16:41:45 : Hello World!