Click here to Skip to main content
Licence 
First Posted 30 Sep 2004
Views 133,859
Bookmarked 190 times

A component for event scheduling inside an application

By | 30 Sep 2004 | Article
This article presents the design and a readily usable component for scheduling events which are consumed inside a server or service application.

Introduction

Every typical server or service application need scheduling of some events inside the application. These events generally are supposed to wake up at certain determined times to do self checks, check statuses of threads, or typically refresh resources once in a while, and so on. This requires shorter and long time scheduling of events inside the application. The most common approach is to use timers for different tasks and attach them to threads. A scheduler component is presented in this article for simplifying a way to create and maintain event scheduling inside an application.

Using the code

The best example to create and use the Schedule classes is in the demo application. This piece of code inside the demo creates all the types of schedule objects implemented in the library, and also provides a delegate ScheduleCallBack() for the schedule to call back for OnTrigger event.

// create and add different types of schedules
Schedule s = new IntervalSchedule("Test_Interval", 
             DateTime.Now.AddMinutes(1), 45, TimeSpan.Zero, 
             new TimeSpan(TimeSpan.TicksPerDay));
s.OnTrigger += new EventScheduler.Invoke(ScheduleCallBack);
Scheduler.AddSchedule(s);

s = new OneTimeSchedule("Test_Onetime", DateTime.Now.AddMinutes(1.5));
s.OnTrigger += new EventScheduler.Invoke(ScheduleCallBack);
Scheduler.AddSchedule(s);

s = new DailySchedule("Test_daily", DateTime.Now.AddMinutes(2));
s.OnTrigger += new EventScheduler.Invoke(ScheduleCallBack);
Scheduler.AddSchedule(s);

s = new WeeklySchedule("Test_weekly", DateTime.Now.AddMinutes(2.5));
s.OnTrigger += new EventScheduler.Invoke(ScheduleCallBack);
Scheduler.AddSchedule(s);

s = new MonthlySchedule("Test_monthly", DateTime.Now.AddMinutes(3));
s.OnTrigger += new EventScheduler.Invoke(ScheduleCallBack);
Scheduler.AddSchedule(s);

As can be seen, the three main lines are to:

  • create a Schedule instance
  • subscribe to the OnTrigger event, and
  • add the Schedule to the Scheduler's list

That's it! To see this in action, run the demo application shown below and click on Test Code button. This will create an instance of each schedule and gives a feeling of what the scheduler can do.

Design and Code details

The following class diagram shows the different classes in the scheduler library and their relationship.

At the root of the library is the Schedule class which implements IComparable interface. The IComparable interface provides the CompareTo(Object) method which is used to compare two Schedule objects for sorting the list of schedules to determine the sequence of invocation times for the timer.

The library already provides general Schedules like OneTimeSchedule (used for raising an event only once), IntervalSchedule (used to raise an event at regular intervals), DailySchedule, WeeklySchedule and MonthlySchedule, which are self explanatory. The Schedule base class has generic properties like Name, Type, NextInvokeTime etc. used by all derived objects, and some specific properties like Interval which is used in this case only by IntervalSchedule.

These are the steps through which the Scheduler goes through for scheduling an event:

  • A static timer (Scheduler.Timer) with a call back method (DispatchEvents) is created and initially put to sleep.
  • Schedules are created either by code or by GUI. Individual conditions are checked in the Schedule's constructor.
  • When ever a Schedule object is added to the Scheduler using AddSchedule(Schedule s) method:
    • the list is sorted. The list which is an ArrayList in turn uses the Schedule.CompareTo(Object) method to determine the sorting order.
    • the NextInvokeTime of the first element in the list is used by the Timer to decide when to wake up next.
  • When the Timer wakes up:
    • it calls DispatchEvents call back
    • which calls TriggerEvents() on the first Schedule object in the list

A Schedule's view GUI is also provided with the library to manage the schedules through a GUI as a singleton class (ScheduleUI) which is created by the static method ScheduleUI.ShowSchedules(). This GUI uses the Scheduler.OnSchedulerEvent event provided by Scheduler to track when a Schedule is created, deleted, or invoked.

Typically, this GUI can be used for administration of schedules and also to create or delete them easily. Once a schedule is created, it can be accessed programmatically using Scheduler events or the name of the Schedule itself.

For e.g., the following code inside ScheduleUI class shows how the Scheduler events are used to refresh the list of Schedules.

public void OnSchedulerEvent(SchedulerEventType type, string scheduleName)
{
    switch(type)
    {
        case SchedulerEventType.CREATED:
            ListViewItem lv = SchedulesView.Items.Add(scheduleName);
            Schedule s = Scheduler.GetSchedule(scheduleName);
            lv.SubItems.Add(s.Type.ToString());
            lv.SubItems.Add(s.NextInvokeTime.ToString("MM/dd/yyyy hh:mm:ss tt"));
            break;
        case SchedulerEventType.DELETED:
            for (int i=0; i<SchedulesView.Items.Count; i++)
                if (SchedulesView.Items[i].Text == scheduleName)
                    SchedulesView.Items.RemoveAt(i);
            break;
        case SchedulerEventType.INVOKED:
            for (int i=0; i<SchedulesView.Items.Count; i++)
                if (SchedulesView.Items[i].Text == scheduleName)
                {
                    Schedule si = Scheduler.GetSchedule(scheduleName);
                    SchedulesView.Items[i].SubItems[2].Text =
                        si.NextInvokeTime.ToString("MM/dd/yyyy hh:mm:ss tt");
                }
            break;
    }
    SchedulesView.Refresh();
}

Another critical piece of code is the bool[] m_workingWeekDays array in the Schedule base class, in which the active week days are stored. The bool NoFreeWeekDay() and bool CanInvokeOnNextWeekDay() use this array to determine if a schedule can run on a week day.

Similarly, the bool IsInvokeTimeInTimeRange() determines if a schedule can run in a time range on any given day. Please refer to comments in the code if you are interested to get into the details.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Sriram Chitturu

Architect

United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Questionquery PinmemberApurva Kunkulol21:41 9 May '12  
GeneralMy vote of 3 Pinmemberprogrammerdon9:18 22 Mar '12  
GeneralMy vote of 5 Pinmembermanoj kumar choubey20:37 12 Feb '12  
Generaltake a look at Quartz PinmemberChris Tracy9:30 17 May '08  
GeneralRe: take a look at Quartz PinmemberJ0J0_3:18 28 Jun '08  
GeneralVS 2008 problem: Cross-thread operation not valid PinmemberMr_AndersonNET23:14 5 May '08  
GeneralRe: VS 2008 problem: Cross-thread operation not valid PinmemberPeeter9:59 15 Jan '10  
AnswerRe: VS 2008 problem: Cross-thread operation not valid PinmemberPrabakar Samiyappan7:23 20 Feb '11  
Questionnew version for schedle? Pinmemberqq344486352:59 10 Apr '08  
QuestionPersist in a database Pinmembercamlopes4:33 21 Jan '08  
GeneralThanks for the idea PinmemberJoseph Wee12:57 27 Nov '07  
GeneralRe: Thanks for the idea PinmemberSriram Chitturi0:06 28 Nov '07  
GeneralRunning without GUI Pinmemberroseen21:51 25 Sep '07  
GeneralRe: Running without GUI Pinmembersamphil2:42 26 Sep '07  
GeneralNew version Pinmemberdima polyakov10:16 21 Sep '07  
After using these classes in couple projects, I found tons of mistakes.
Here is my version that I use (it is also not perfect, but IMHO more usefull). There are changes basically in every class:
 
Schedule.cs

using System;
using System.Threading;
 
namespace EventScheduler
{
// delegate for OnTrigger() event
public delegate void Invoke(string scheduleName);
 
// enumeration for schedule types
public enum ScheduleType { ONETIME, INTERVAL, DAILY, WEEKLY, MONTHLY };
 
// base class for all schedules
abstract public class Schedule : IComparable
{
public event Invoke OnTrigger;
protected string m_name; // name of the schedule
protected ScheduleType m_type; // type of schedule
protected bool m_active; // is schedule active ?
 
protected DateTime m_nextTime; // time when this schedule is invoked next, used by scheduler
 
// m_fromTime and m_toTime are used to defined a time range during the day
// between which the schedule can run.
// This is useful to define a range of working hours during which a schedule can run
protected TimeSpan m_fromTime;
protected TimeSpan m_toTime;
 
// Array containing the 7 weekdays and their status
// Using DayOfWeek enumeration for index of this array
bool[] m_workingWeekDays = new bool[]{true, true, true, true, true, true, true};
 
// time interval used by schedules like IntervalSchedule
protected TimeSpan m_interval = new TimeSpan();
 
public void SetWorkingDaysOnly()
{
SetWeekDay(DayOfWeek.Monday, true);
SetWeekDay(DayOfWeek.Tuesday, true);
SetWeekDay(DayOfWeek.Wednesday, true);
SetWeekDay(DayOfWeek.Thursday, true);
SetWeekDay(DayOfWeek.Friday, true);
SetWeekDay(DayOfWeek.Saturday, false);
SetWeekDay(DayOfWeek.Sunday, false);
}
 
// Accessor for type of schedule
public ScheduleType Type
{
get { return m_type; }
}
 
// Accessor for name of schedule
// Name is set in constructor only and cannot be changed
public string Name
{
get { return m_name; }
}
 
public bool Active
{
get { return m_active; }
set { m_active = value; }
}
 
// check if no week days are active
protected bool NoFreeWeekDay()
{
bool check = false;
for (int index=0; index<7; check = check|m_workingWeekDays[index], index++);
return check;
}
 
// Setting the status of a week day
public void SetWeekDay(DayOfWeek day, bool On)
{
m_workingWeekDays[(int)day] = On;
Active = true; // assuming
 
// Make schedule inactive if all weekdays are inactive
// If a schedule is not using the weekdays the array should not be touched
if (NoFreeWeekDay())
Active = false;
}
 
// Return if the week day is set active
public bool WeekDayActive(DayOfWeek day)
{
return m_workingWeekDays[(int)day];
}
 
// Method which will return when the Schedule has to be invoked next
// This method is used by Scheduler for sorting Schedule objects in the list
public DateTime NextInvokeTime
{
get { return m_nextTime; }
}
 
// Accessor for m_interval in seconds
// Put a lower limit on the interval to reduce burden on resources
// I am using a lower limit of 30 seconds
public TimeSpan Interval
{
get { return m_interval; }
set {
if (value.TotalSeconds < 1)
throw new SchedulerException("Interval cannot be less than 1 second");
m_interval = value;
}
}
 
// Constructor
public Schedule(string name, ScheduleType type)
{
m_type = type;
m_name = name;
m_nextTime = DateTime.Now;
}
 
// Sets the next time this Schedule is kicked off and kicks off events on
// a seperate thread, freeing the Scheduler to continue
public void TriggerEvents()
{
CalculateNextInvokeTime(); // first set next invoke time to continue with rescheduling
ThreadStart ts = new ThreadStart(KickOffEvents);
Thread t = new Thread(ts);
t.Start();
}
 
// Implementation of ThreadStart delegate.
// Used by Scheduler to kick off events on a seperate thread
private void KickOffEvents()
{
if (OnTrigger != null)
OnTrigger(Name);
}
 
// To be implemented by specific schedule objects when to invoke the schedule next
internal abstract void CalculateNextInvokeTime();
 
// check to see if the Schedule can be invoked on the week day it is next scheduled
protected bool CanInvokeOnNextWeekDay()
{
return m_workingWeekDays[(int)m_nextTime.DayOfWeek];
}
 
// Check to see if the next time calculated is within the time range
// given by m_fromTime and m_toTime
// The ranges can be during a day, for eg. 9 AM to 6 PM on same day
// or overlapping 2 different days like 10 PM to 5 AM (i.e over the night)
protected bool IsInvokeTimeInTimeRange()
{
if (m_fromTime < m_toTime) // eg. like 9 AM to 6 PM
return (m_nextTime.TimeOfDay >= m_fromTime && m_nextTime.TimeOfDay <= m_toTime);
else // eg. like 10 PM to 5 AM
return (m_nextTime.TimeOfDay >= m_toTime && m_nextTime.TimeOfDay <= m_fromTime);
}
 
// IComparable interface implementation is used to sort the array of Schedules
// by the Scheduler
public int CompareTo(object obj)
{
if (obj is Schedule)
{
return m_nextTime.CompareTo(((Schedule)obj).m_nextTime);
}
throw new Exception("Not a Schedule object");
}
}
}

 
Scheduler.cs
using System;
using System.Threading;
using System.Collections;
 
namespace EventScheduler
{
// enumeration of Scheduler events used by the delegate
public enum SchedulerEventType { CREATED, DELETED, INVOKED };
 
// delegate for Scheduler events
public delegate void SchedulerEventDelegate(SchedulerEventType type, string scheduleName);
 
// This is the main class which will maintain the list of Schedules
// and also manage them, like rescheduling, deleting schedules etc.
public sealed class Scheduler
{
// Event raised when for any event inside the scheduler
static public event SchedulerEventDelegate OnSchedulerEvent;
 
// next event which needs to be kicked off,
// this is set when a new Schedule is added or after invoking a Schedule
static Schedule m_nextSchedule = null;
static ArrayList m_schedulesList = new ArrayList(); // list of schedules
static Timer m_timer = new Timer(new TimerCallback(DispatchEvents), // main timer
null,
Timeout.Infinite,
Timeout.Infinite);
 
// Get schedule at a particular index in the array list
public static Schedule GetScheduleAt(int index)
{
if (index < 0 || index >= m_schedulesList.Count)
return null;
return (Schedule)m_schedulesList[index];
}
 
// Number of schedules in the list
public static int Count()
{
return m_schedulesList.Count;
}
 
// Indexer to access a Schedule object by name
public static Schedule GetSchedule(string scheduleName)
{
for (int index=0; index < m_schedulesList.Count; index++)
if (((Schedule)m_schedulesList[index]).Name == scheduleName)
return (Schedule)m_schedulesList[index];
return null;
}
 
// call back for the timer function
static void DispatchEvents(object obj) // obj ignored
{
if (m_nextSchedule == null)
return;
m_nextSchedule.TriggerEvents(); // make this happen on a thread to let this thread continue
if (m_nextSchedule.Type == ScheduleType.ONETIME)
{
RemoveSchedule(m_nextSchedule); // remove the schedule from the list
}
else
{
if (OnSchedulerEvent != null)
OnSchedulerEvent(SchedulerEventType.INVOKED, m_nextSchedule.Name);
m_schedulesList.Sort();
SetNextEventTime();
}
}
 
// method to set the time when the timer should wake up to invoke the next schedule
static void SetNextEventTime()
{
if (m_schedulesList.Count == 0)
{
m_timer.Change(Timeout.Infinite, Timeout.Infinite); // this will put the timer to sleep
return;
}
m_nextSchedule = (Schedule)m_schedulesList[0];
TimeSpan ts = m_nextSchedule.NextInvokeTime.Subtract(DateTime.Now);
if (ts < TimeSpan.Zero)
ts = TimeSpan.Zero; // time already past, set timer to 0 to execute callback
m_timer.Change((int)ts.TotalMilliseconds, Timeout.Infinite); // invoke after the timespan
}
 
// add a new schedule
public static void AddSchedule(Schedule s)
{
if (GetSchedule(s.Name) != null)
throw new SchedulerException("Schedule with the same name already exists");
m_schedulesList.Add(s);
m_schedulesList.Sort();
// adjust the next event time if schedule is added at the top of the list
if (m_schedulesList[0] == s)
SetNextEventTime();
if (OnSchedulerEvent != null)
OnSchedulerEvent(SchedulerEventType.CREATED, s.Name);
}
 
// remove a schedule object from the list
public static void RemoveSchedule(Schedule s)
{
m_schedulesList.Remove(s);
SetNextEventTime();
if (OnSchedulerEvent != null)
OnSchedulerEvent(SchedulerEventType.DELETED, s.Name);
}
 
// remove all schedules
public static void RemoveAllSchedules()
{
while(m_schedulesList.Count > 0)
{
String name = ((Schedule)m_schedulesList[0]).Name;
m_schedulesList.Remove((Schedule)m_schedulesList[0]);
SetNextEventTime();
if(OnSchedulerEvent != null)
OnSchedulerEvent(SchedulerEventType.DELETED, name);
}
}
 
// remove schedule by name
public static void RemoveSchedule(string name)
{
RemoveSchedule(GetSchedule(name));
}
}
}

 
SchedulerExceptions.cs
using System;
 
namespace EventScheduler
{
///
/// Summary description for SchedulerException.
///

public class SchedulerException : Exception
{
public SchedulerException(string msg) : base(msg)
{
}
}
}

 
ScheduleTypes.cs
using System;
 
namespace EventScheduler
{
// OneTimeSchedule is used to schedule an event to run only once
// Used by specific tasks to check self status
public class OneTimeSchedule : Schedule
{
public OneTimeSchedule(String name, DateTime startTime)
: base(name, ScheduleType.ONETIME)
{
m_nextTime = startTime;
}
internal override void CalculateNextInvokeTime()
{
// it does not matter, since this is a one time schedule
m_nextTime = DateTime.MaxValue;
}
}
 
// IntervalSchedule is used to schedule an event to be invoked at regular intervals
// the interval is specified in seconds. Useful mainly in checking status of threads
// and connections. Use an interval of 60 hours for an hourly schedule
public class IntervalSchedule : Schedule
{
public IntervalSchedule(String name, TimeSpan TimeInterval,
TimeSpan fromTime, TimeSpan toTime) // time range for the day
: base(name, ScheduleType.INTERVAL)
{
if(TimeInterval.Ticks >= TimeSpan.TicksPerDay)
throw new SchedulerException("TimeInterval > max ticks per day");
if(fromTime.Ticks >= TimeSpan.TicksPerDay)
throw new SchedulerException("fromTime > max ticks per day");
if(toTime.Ticks >= TimeSpan.TicksPerDay)
throw new SchedulerException("toTime > max ticks per day");
 
m_fromTime = fromTime;
m_toTime = toTime;
Interval = TimeInterval;
 
DateTime now = DateTime.Now;
 
DateTime start = new DateTime(now.Year, now.Month, now.Day, m_fromTime.Hours, m_fromTime.Minutes, m_fromTime.Seconds, m_fromTime.Milliseconds);
DateTime end = new DateTime(now.Year, now.Month, now.Day, m_toTime.Hours, m_toTime.Minutes, m_toTime.Seconds, m_toTime.Milliseconds);
 
m_nextTime = start;
 
if(fromTime < toTime)
{
do
{
if(now <= start)
break;
 
if(now >= end || now + TimeInterval >= end)
{
m_nextTime = start.AddDays(1);
break;
}
 
long ticks_from_start = now.TimeOfDay.Ticks - start.TimeOfDay.Ticks;
long whole_past_ticks_intervals = ticks_from_start / TimeInterval.Ticks;
 
start = start.AddTicks(TimeInterval.Ticks * whole_past_ticks_intervals + TimeInterval.Ticks);
} while(false);
}
else
throw new SchedulerException("Not supported time range");
 
m_nextTime = start;
}
 
internal override void CalculateNextInvokeTime()
{
// add the interval of m_seconds
m_nextTime = m_nextTime.AddTicks(Interval.Ticks);
 
// if next invoke time is not within the time range, then set it to next start time
if (! IsInvokeTimeInTimeRange())
{
Boolean bAddDay = false;
if(m_nextTime.TimeOfDay > m_toTime)
bAddDay = true;
 
// set m_nextTime to the beginning of a new day
m_nextTime = new DateTime(m_nextTime.Year, m_nextTime.Month, m_nextTime.Day, m_fromTime.Hours, m_fromTime.Minutes, m_fromTime.Seconds, m_fromTime.Milliseconds);

if(bAddDay)
m_nextTime = m_nextTime.AddDays(1);
}
 
// check to see if the next invoke time is on a working day
while(!CanInvokeOnNextWeekDay())
m_nextTime = m_nextTime.AddDays(1); // start checking on the next day
}
}
 
// Daily schedule is used set off to the event every day
// Mainly useful in maintanance, recovery, logging and report generation
// Restictions can be imposed on the week days on which to run the schedule
public class DailySchedule : Schedule
{
public DailySchedule(String name, TimeSpan startTime)
: base(name, ScheduleType.DAILY)
{
if(startTime.Ticks >= TimeSpan.TicksPerDay)
throw new SchedulerException("startTime > max ticks per day");
 
DateTime current = DateTime.Now;
 
DateTime today_start = new DateTime(current.Year, current.Month, current.Day, startTime.Hours, startTime.Minutes, startTime.Seconds, startTime.Milliseconds);
 
int res = DateTime.Compare(current, today_start);
if(res > 0)// current > start_time
today_start = today_start.AddDays(1);
 
m_nextTime = today_start;
}
 
internal override void CalculateNextInvokeTime()
{
// add a day, and check for any weekday restrictions and keep adding a day
m_nextTime = m_nextTime.AddDays(1);
 
while(!CanInvokeOnNextWeekDay())
m_nextTime = m_nextTime.AddDays(1);
}
}
 
// Weekly schedules
public class WeeklySchedule : Schedule
{
public WeeklySchedule(String name, DateTime startTime)
: base(name, ScheduleType.WEEKLY)
{
m_nextTime = startTime;
}
 
public WeeklySchedule(String name, DayOfWeek day, TimeSpan time)
: base(name, ScheduleType.WEEKLY)
{
DateTime now = DateTime.Now;
DateTime this_week = now.Date.AddDays(-(int)now.DayOfWeek);
 
m_nextTime = this_week.Add(time);
 
if(m_nextTime <= DateTime.Now)
CalculateNextInvokeTime();
}

// add a week (or 7 days) to the date
internal override void CalculateNextInvokeTime()
{
m_nextTime = m_nextTime.AddDays(7);
}
}
 
// Monthly schedule - used to kick off an event every month on the same day as scheduled
// and also at the same hour and minute as given in start time
public class MonthlySchedule : Schedule
{
public MonthlySchedule(String name, DateTime startTime)
: base(name, ScheduleType.MONTHLY)
{
m_nextTime = startTime;
}
public MonthlySchedule(String name, TimeSpan startDateTimeFromTheBeginningOfTheMonth)
: base(name, ScheduleType.MONTHLY)
{
DateTime now = DateTime.Now;
 
DateTime dt = new DateTime(now.Year, now.Month, 1) + startDateTimeFromTheBeginningOfTheMonth;
 
dt = dt.AddDays(-1);
 
if(dt < now)
dt = dt.AddMonths(1);
 
m_nextTime = dt;
}
// add a month to the present time
internal override void CalculateNextInvokeTime()
{
m_nextTime = m_nextTime.AddMonths(1);
}
}
}

 
Dima
http://www.mmexplorer.com[^]
GeneralRe: New version Pinmemberingos200711:23 22 Sep '07  
GeneralRe: New version Pinmemberdima polyakov10:56 23 Sep '07  
GeneralRe: New version Pinmembersamphil2:40 26 Sep '07  
GeneralRe: New version Pinmemberdima polyakov5:07 26 Sep '07  
GeneralPerhaps you should read up on 'lock' Pinmemberrobvon23:20 18 Sep '07  
GeneralFIX - Intervals were not expiring. Pinmemberkurios11:22 23 Aug '07  
GeneralPlz upload the updated version PinmemberBill_Gates21:01 26 Feb '07  
GeneralNew Programmer PinmemberDoritkatz23:28 20 Jan '07  
GeneralRe: New Programmer Pinmembertridex3:48 18 Jun '07  
Questiona gread deal of schedues will to run Pinmemberhou12613:39 14 Nov '06  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120529.1 | Last Updated 1 Oct 2004
Article Copyright 2004 by Sriram Chitturu
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid