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.