Click here to Skip to main content
Click here to Skip to main content
Go to top

A component for event scheduling inside an application

, 30 Sep 2004
Rate this:
Please Sign up or sign in to vote.
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

Share

About the Author

Sriram Chitturi
Architect
United States United States
No Biography provided

Comments and Discussions

 
Questionnew version for schedle? Pinmemberqq3444863510-Apr-08 2:59 
QuestionPersist in a database Pinmembercamlopes21-Jan-08 4:33 
GeneralThanks for the idea PinmemberJoseph Wee27-Nov-07 12:57 
GeneralRe: Thanks for the idea PinmemberSriram Chitturi28-Nov-07 0:06 
GeneralRunning without GUI Pinmemberroseen25-Sep-07 21:51 
GeneralRe: Running without GUI Pinmembersamphil26-Sep-07 2:42 
GeneralNew version Pinmemberdima polyakov21-Sep-07 10:16 
GeneralRe: New version Pinmemberingos200722-Sep-07 11:23 
GeneralRe: New version Pinmemberdima polyakov23-Sep-07 10:56 
GeneralRe: New version Pinmembersamphil26-Sep-07 2:40 
GeneralRe: New version Pinmemberdima polyakov26-Sep-07 5:07 
GeneralPerhaps you should read up on 'lock' Pinmemberrobvon18-Sep-07 23:20 
GeneralFIX - Intervals were not expiring. Pinmemberkurios23-Aug-07 11:22 
GeneralPlz upload the updated version PinmemberBill_Gates26-Feb-07 21:01 
GeneralNew Programmer PinmemberDoritkatz20-Jan-07 23:28 
GeneralRe: New Programmer Pinmembertridex18-Jun-07 3:48 
Questiona gread deal of schedues will to run Pinmemberhou12614-Nov-06 13:39 
GeneralA great article PinmemberAsad_KA22-Sep-06 10:59 
QuestionEvent Scheduler PinmemberNicos Andreou20-Sep-06 23:01 
QuestionHow to have params passed into ScheduleCallBack Pinmemberhannalu14-Feb-06 12:33 
AnswerRe: How to have params passed into ScheduleCallBack PinmemberBraveShogun19-Dec-06 1:45 
Generalsupport / bugfixes PinmemberKylixs9-Oct-05 7:05 
GeneralRe: support / bugfixes [modified] PinmemberGonzalo Brusella23-Jun-06 9:10 
GeneralRe: support / bugfixes PinmemberDanilo Corallo30-Aug-06 3:37 
GeneralRe: support / bugfixes PinmemberGonzalo Brusella30-Aug-06 4:23 
GeneralThreads problem Pinmemberfredrikp22-Aug-05 5:20 
GeneralRe: Threads problem PinsussAnonymous28-Aug-05 13:16 
GeneralNovice User How to integrate with existing code Pinmemberckandreou21-Jun-05 10:29 
GeneralVb.net Pinmembertobbylee1325-May-05 9:06 
GeneralRe: Vb.net PinmemberBenjamin Hall14-Jun-05 13:04 
GeneralRe: Vb.net PinmemberDoritkatz20-Jan-07 23:27 
QuestionRe: Vb.net Pinmembercorym26-Jul-07 2:39 
GeneralWeekdays bug Pinmemberyesildal8-Apr-05 16:59 
QuestionUpdates? PinmemberMatt Philmon6-Apr-05 7:35 
AnswerRe: Updates? Pinmembersbouli30-May-05 2:39 
GeneralRe: Updates? PinmemberDanilo Corallo30-Aug-06 3:36 
GeneralSriram Pinmembermike_oop14-Mar-05 5:31 
GeneralSerialized Schedules PinmemberPaul Patterson8-Mar-05 4:33 
GeneralRe: Serialized Schedules PinmemberDanilo Corallo23-Aug-06 22:52 
Generalschedule a method call Pinmembercheelam_mze24-Feb-05 0:57 
QuestionRe: schedule a method call PinmemberBraveShogun19-Dec-06 1:51 
GeneralSetNextEventTime() PinmemberStar933-Jan-05 13:55 
GeneralThanks! Pinmembernetclectic19-Nov-04 3:06 
GeneralFix in SetNextEventTime PinmemberGjalt21-Oct-04 2:27 
GeneralA problem with Scheduler Pinmemberabolourian20-Oct-04 6:00 
GeneralRe: A problem with Scheduler PinmemberStar938-Apr-05 7:56 
GeneralSolution PinmemberStar9315-Apr-05 9:28 
GeneralAddition to the solution PinmemberNetaKadosh5-Feb-07 20:16 
GeneralRe: A problem with Scheduler PinmemberRoji Jacob14-Apr-09 2:16 
Generaluse it in web app Pinmembersamham19-Oct-04 0:03 

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.

| Advertise | Privacy | Mobile
Web02 | 2.8.140905.1 | Last Updated 1 Oct 2004
Article Copyright 2004 by Sriram Chitturi
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid