Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | E-Books | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
World Class ASP.NET Hosting - 3 Month Free Hosting, Click Here!
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » XML .NET » Application Scheduler Service Using C#.Net And XML

Application Scheduler Service Using C#.Net And XML

This is an application scheduler that is implemented as a Windows Service, similar to the Windows Task Scheduler - but simple, as it has fewer configuration options and it uses XML to store and retrieve data.

Technologies: .NET 1.0/1.1, .NET 1.0/1.1, XML,Visual C# .NET
Total downloads : 6183
Total page views :  101238
Rating :
 4.75/5
This article has been rated :  12 times
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
AppScheduler.zip | AppScheduler_XML.zip
 
Become a Sponsor



This is an application scheduler that is implemented as a Windows Service, similar to the Windows Task Scheduler - but simple, as it has fewer configuration options and it uses XML to store and retrieve data.

 

The program uses System.Timers, System.Threading and System.Diagnostics to repeatedly loop through the XML data to see whether an application is scheduled to run at the present time or not, and if yes, to launch it as a new process in a new thread.

 

The source

 

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Diagnostics;

using System.ServiceProcess;

using System.Xml;

using System.Timers;

using System.Threading;

using System.Configuration;

using System.IO;

 

namespace AppScheduler

{

      public class AppScheduler : System.ServiceProcess.ServiceBase

      {

            string configPath;

            System.Timers.Timer _timer=new System.Timers.Timer();

            DataSet ds=new DataSet();

            /// <summary>

            /// Required designer variable.

            /// </summary>

            private System.ComponentModel.Container components = null;

 

        /// <summary>

        /// Class that launches applications on demand.

        /// </summary>

            class AppLauncher

            {

                  string app2Launch;

                  public AppLauncher(string path)

                  {

                        app2Launch=path;

                  }

                  public void runApp()

                  {

                        ProcessStartInfo pInfo=new ProcessStartInfo(app2Launch);

                        pInfo.WindowStyle=ProcessWindowStyle.Normal;

                        Process p=Process.Start(pInfo);

                  }

            }

 

            void timeElapsed(object sender, ElapsedEventArgs args)

            {

                  DateTime currTime=DateTime.Now;

                  foreach(DataRow dRow in ds.Tables["task"].Rows)

                  {

                        DateTime runTime=Convert.ToDateTime(dRow["time"]);

                        string formatString="MM/dd/yyyy HH:mm";

                        if(runTime.ToString(formatString)==currTime.ToString(formatString))

                        {

                              string exePath=dRow["exePath"].ToString();

                              AppLauncher launcher=new AppLauncher(exePath);

                              new Thread(new ThreadStart(launcher.runApp)).Start();

                              // Update the next run time

                              string strInterval=dRow["repeat"].ToString().ToUpper();

                              switch(strInterval)

                              {

                                    case "D":

                                          runTime=runTime.AddDays(1);

                                          break;

                                    case "W":

                                          runTime=runTime.AddDays(7);

                                          break;

                                    case "M":

                                          runTime=runTime.AddMonths(1);

                                          break;

                              }

                              dRow["time"]=runTime.ToString(formatString);

                              ds.AcceptChanges();

                              StreamWriter sWrite=new StreamWriter(configPath);

                              XmlTextWriter xWrite=new XmlTextWriter(sWrite);

                              ds.WriteXml(xWrite, XmlWriteMode.WriteSchema);

                              xWrite.Close();

                        }

                  }

            }

 

            public AppScheduler()

            {

                  // This call is required by the Windows.Forms Component Designer.

                  InitializeComponent();

 

                  // TODO: Add any initialization after the InitComponent call

            }

 

            // The main entry point for the process

            static void Main()

            {

                  System.ServiceProcess.ServiceBase[] ServicesToRun;

     

                  // More than one user Service may run within the same process. To add

                  // another service to this process, change the following line to

                  // create a second service object. For example,

                  //

                  //   ServicesToRun = new System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};

                  //

                  ServicesToRun = new System.ServiceProcess.ServiceBase[] { new AppScheduler() };

 

                  System.ServiceProcess.ServiceBase.Run(ServicesToRun);

            }

 

            /// <summary>

            /// Required method for Designer support - do not modify

            /// the contents of this method with the code editor.

            /// </summary>

            private void InitializeComponent()

            {

                  //

                  // AppScheduler

                  //

                  this.CanPauseAndContinue = true;

                  this.ServiceName = "Application Scheduler";

 

            }

 

            /// <summary>

            /// Clean up any resources being used.

            /// </summary>

            protected override void Dispose( bool disposing )

            {

                  if( disposing )

                  {

                        if (components != null)

                        {

                              components.Dispose();

                        }

                  }

                  base.Dispose( disposing );

            }

 

            /// <summary>

            /// Set things in motion so your service can do its work.

            /// </summary>

            protected override void OnStart(string[] args)

            {

                  // TODO: Add code here to start your service.

                  configPath=ConfigurationSettings.AppSettings["configpath"];

                  try

                  {

                        XmlTextReader xRead=new XmlTextReader(configPath);

                        XmlValidatingReader xvRead=new XmlValidatingReader(xRead);

                        xvRead.ValidationType=ValidationType.DTD;

                        ds.ReadXml(xvRead);

                        xvRead.Close();

                        xRead.Close();

                  }

                  catch(Exception)

                  {

                        ServiceController srvcController=new ServiceController(ServiceName);

                        srvcController.Stop();

                  }

                  _timer.Interval=30000;

                  _timer.Elapsed+=new ElapsedEventHandler(timeElapsed);

                  _timer.Start();

            }

 

            /// <summary>

            /// Stop this service.

            /// </summary>

            protected override void OnStop()

            {

                  // TODO: Add code here to perform any tear-down necessary to stop your service.

            }

      }

}

 

I have created a class named AppLauncher that accepts the executable name of a program as its constructor parameter. There is a method RunApp() in the class that creates a new ProcessInfo object with the specified path and calls Process.Start(ProcessInfo) with the ProcessInfo object as its parameter.

 

Class that launches applications on demand

 

class AppLauncher

{

      string app2Launch;

      public AppLauncher(string path)

      {

            app2Launch=path;

      }

      public void runApp()

      {

            ProcessStartInfo pInfo=new ProcessStartInfo(app2Launch);

            pInfo.WindowStyle=ProcessWindowStyle.Normal;

            Process p=Process.Start(pInfo);

      }

}

 

I had to create a separate class to launch an application in a new thread, because the Thread class in .Net 2003 does not allow you to pass parameters to a thread delegate (whereas you can do so in .Net 2005). The ProcessStartInfo class can be used to create a new process. The static method Start (ProcessInfo) of the Process class returns a Process object that represents the process started.

 

There is a Timer variable used in the program, named _timer. The event handler for the timer's tick event is given below:

 

Event handler for the timer's tick event

 

void timeElapsed(object sender, ElapsedEventArgs args)

{

      DateTime currTime=DateTime.Now;

      foreach(DataRow dRow in ds.Tables["task"].Rows)

      {

            DateTime runTime=Convert.ToDateTime(dRow["time"]);

            string formatString="MM/dd/yyyy HH:mm";

            if(runTime.ToString(formatString)==currTime.ToString(formatString))

            {

                  string exePath=dRow["exePath"].ToString();

                  AppLauncher launcher=new AppLauncher(exePath);

                  new Thread(new ThreadStart(launcher.runApp)).Start();

                  // Update the next run time

                  string strInterval=dRow["repeat"].ToString().ToUpper();

                  switch(strInterval)

                  {

                        case "D":

                              runTime=runTime.AddDays(1);

                              break;

                        case "W":

                              runTime=runTime.AddDays(7);

                              break;

                        case "M":

                              runTime=runTime.AddMonths(1);

                              break;

                  }

                  dRow["time"]=runTime.ToString(formatString);

                  ds.AcceptChanges();

                  StreamWriter sWrite=new StreamWriter(configPath);

                  XmlTextWriter xWrite=new XmlTextWriter(sWrite);

                  ds.WriteXml(xWrite, XmlWriteMode.WriteSchema);

                  xWrite.Close();

            }

      }

}

 

An easy way to compare date and time disregarding some particular values such as hour of the day or minute or second: convert them to the appropriate string format first, and check whether the two strings are equal. Otherwise, you have to individually check each item you want to compare, like if(currTime.Day==runtime.Day && currTime.Month==runtime.Month && ...). The interval values are : "D" (for daily schedule), "W" (for weekly schedule), and "M" (for monthly schedule). The values are read from an XML file named AppScheduler.xml. The file format is given below:

 

The XML file containing list of applications to launch

 

<?xml version="1.0" encoding="utf-8" ?>

<!DOCTYPE appSchedule[

<!ELEMENT appSchedule (task*)>

<!ELEMENT task EMPTY>

<!ATTLIST task name CDATA #REQUIRED>

<!ATTLIST task exePath CDATA #REQUIRED>

<!ATTLIST task time CDATA #REQUIRED>

<!ATTLIST task repeat (D|W|M) #REQUIRED>

]>

<appSchedule>

          <task name="Notepad" exePath="%SystemRoot%\system32\notepad.exe" time="05/05/2006 10:45" repeat="D"/>

          <task name="Wordpad" exePath="C:\Program Files\Outlook Express\msimn.exe" time="05/05/2006 10:46" repeat="W"/>

          <task name="Calculator" exePath="%SystemRoot%\System32\calc.exe" time="05/05/2006 10:47" repeat="M"/>

</appSchedule>

 

Starting the service

 

protected override void OnStart(string[] args)

{

      // TODO: Add code here to start your service.

      configPath=ConfigurationSettings.AppSettings["configpath"];

      try

      {

            XmlTextReader xRead=new XmlTextReader(configPath);

            XmlValidatingReader xvRead=new XmlValidatingReader(xRead);

            xvRead.ValidationType=ValidationType.DTD;

            ds.ReadXml(xvRead);

            xvRead.Close();

            xRead.Close();

      }

      catch(Exception)

      {

            ServiceController srvcController=new ServiceController(ServiceName);

            srvcController.Stop();

      }

      _timer.Interval=30000;

      _timer.Elapsed+=new ElapsedEventHandler(timeElapsed);

      _timer.Start();

}

 

The path of the XML file is set in the App.config file (the IDE will not create this file automatically, so you will have to manually add one into your project) in the following way:

 

App.config

 

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

          <appSettings>

                   <add key="configpath" value="C:\AppScheduler.xml"/>

          </appSettings>

</configuration>

 

An XmlValidatingReader is used to ensure that the data strictly confirms to the DTD. The catch block stops the service, if some error occurs while trying to load data from the XML file. The timer interval is set to 30 seconds on starting the service.

 

To install/unistall the service

 

Build the application. Copy the AppScheduler.xml file to your C:\. Select Start > Programs > Microsoft Visual Studio .NET 2003 > Visual Studio .NET Tools > Visual Studio .NET 2003 Command Prompt. Go to the \bin\release folder in the project directory. Type the following command:

 

installutil AppScheduler.exe

 

Now, go to control panel. Select Performance and Maintenance > Administrative Tools and select Services. Doble-click on the AppScheduler service. Select the Log on tab. Check the Allow this service to interact with desktop checkbox. Click OK. Then click on the Start Service(}) button in the toolbar.

 

To uninstall the service, in the Visual Studio .NET command prompt, go to the \bin\release folder in the project directory and enter:

 

installutil /u AppScheduler.exe

 

Summary

 

Creating Windows services is fun, once you learn the basic things to do. XML is really a great tool that makes lot simple to define data and behavior using plain text files.


Login to add your contents and source code to this article
 [Top] Rate this article
 About the author
 
Ajith Kumar Radhakrishnan
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Microsoft Visual Studio 2010 offers more to developers than any other Visual Studio release. Work more productively and collaboratively-with greater control over your work at every step. The Beta 2 can give you a head start on achieving efficiency.
 
   Print Read/Post comments Post a comment  Rate  
   Email to a friend  Bookmark  Similar Articles  Author's other articles  
Download Files:
AppScheduler.zip | AppScheduler_XML.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Completing the service technology by LucasPonzo On June 14, 2006

Hi,

Very nice your article. When I thinked about place it on my production server, I then remember an important question: How to perform a remote (from client machine) configuration of the service.

Some like this: Develop a console (MMC) that connects to the service and the service configures the server local XML file through the remote client command.

There is some example on this ?

Is some thing that can be a continuation of your article (a sugestion).

Best Regards,

Lucas Ponzo.

Reply | Email | Delete | Modify | 
Continuously monitoring XML File and starting the applications by Mohammed On August 22, 2006
This articel gave me a very good introduction on scheduling tasks. I tried to change the XML file and modified the timings but this service does not schedule at that time. Is this possible?
Reply | Email | Delete | Modify | 
Exe File Mention in XML File not Open when Schedule time Reached by Senthil On April 3, 2007
Article is Nice, The Exe File is not Triggering according to Time which i set in the XML File
Reply | Email | Delete | Modify | 
Exe File Mention in XML File not Open when Schedule time Reached by Senthil On April 3, 2007
Article is Nice, The Exe File is not Triggering according to Time which i set in the XML File
Reply | Email | Delete | Modify | 
Re: Exe File Mention in XML File not Open when Schedule time Reached by Ajith Kumar On April 27, 2007
I think there might be some problem related with parsing the date/time. Can you try changing the date/time format of your PC? Note that I've used the format "05/05/2006 10:45" in the XML.
Reply | Email | Delete | Modify | 
Re: Re: Exe File Mention in XML File not Open when Schedule time Reached by Dinu On May 10, 2007
By 05/05/2007, You mean "dd/mm/yy" or "mm/dd/yy". Do I need to attach AM/PM with the time. Anyway I also have the same problem.Exe File Mention in XML File not Open when Schedule time Reached Dinu
Reply | Email | Delete | Modify | 
Re: Re: Exe File Mention in XML File not Open when Schedule time Reached by anu On September 17, 2008

Hi Ajith

  I have copied this Code into my new Project.I am facing Problem in installation of AppScheduler.exe as it has not created in my project. solution is building successfully.From where i Should install this exe.
Please reply me ASAP..

Reply | Email | Delete | Modify | 
running as System and DTD by jonathan On February 5, 2008
Note that any processes started by the service will only be visible if the service runs as the System account with the ability to interact with the desktop. Also, when I run the service, it updates the XML file with the next run time as it should, but it also remooves the DOCTYPE, so that the next time I read the XML file, I can't do a validation against the DTD. Any thoughts on how to get the DOCTYPe info to stay?
Reply | Email | Delete | Modify | 
New XML Validation Code by y2k4life On February 11, 2008
I ran this under .NET 3.5 and got an obsolete on the validation of the XML. I made the following code changes: XmlReaderSettings settings = new XmlReaderSettings(); settings.ProhibitDtd = false; settings.ValidationType = ValidationType.DTD; XmlReader reader = XmlReader.Create(filename, settings); _schedule.Clear(); _schedule.ReadXml(reader); reader.Close();
Reply | Email | Delete | Modify | 
Updating and Reading the schedule by y2k4life On February 15, 2008
The schedule is cached in a DataSet, but never reloaded after the service is started. If the schedule is modified then one would have to shut down and start again. I would made a LoadSchedule method and called it from the start event along with the timer interval event. This would make sure if the file change by other means it would be loaded. More logic could be add to compare dates or something as to maybe cut down on the amount of reads but at least this might be a bit better. Another things is to move the update of the schedule before running it. Two things happen the reschulde will be one Day plus how ever long it take to run the process. One day it starts at 12:00 runs for 30 minutes next day starts at 12:30 the next 1:00. Also if the process crashes then then bumping up the schedule does not happen. I would move this before running the process. One last thing would be some error handling to log into the event log if something does go wrong. Great foundation to work from thanx.
Reply | Email | Delete | Modify | 
nice stuff by Manish On December 26, 2008
Ajith I found this stuff very helpful because I also wanted to make such a program. I'd like to know whether this service needs any window User ID to run .
Reply | Email | Delete | Modify | 
Thank you! by chris On January 13, 2009
This is a great starting point for what I need to do, exactly what I was going to write but now I don't have to, thank you!
Reply | Email | Delete | Modify | 
greate Work by hemantk On August 11, 2009
you are the man....you have done greate work...thankx....
Reply | Email | Delete | Modify | 
abt Code by Ajay On October 20, 2009
Nice article
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2009  Mindcracker LLC. All Rights Reserved