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
1
using
System;
2
3
using
System.Collections;
4
5
using
System.ComponentModel;
6
7
using
System.Data;
8
9
using
System.Diagnostics;
10
11
using
System.ServiceProcess;
12
13
using
System.Xml;
14
15
using
System.Timers;
16
17
using
System.Threading;
18
19
using
System.Configuration;
20
21
using
System.IO;
22
23
24
25
namespace
AppScheduler
26
27
{
28
29 public class AppScheduler : System.ServiceProcess.ServiceBase
30
31 {
32
33 string configPath;
34
35 System.Timers.Timer _timer=new System.Timers.Timer();
36
37 DataSet ds=new DataSet();
38
39 /**//// <summary>
40
41 /// Required designer variable.
42
43 /// </summary>
44
45 private System.ComponentModel.Container components = null;
46
47
48
49 /**//// <summary>
50
51 /// Class that launches applications on demand.
52
53 /// </summary>
54
55 class AppLauncher
56
57 {
58
59 string app2Launch;
60
61 public AppLauncher(string path)
62
63 {
64
65 app2Launch=path;
66
67 }
68
69 public void runApp()
70
71 {
72
73 ProcessStartInfo pInfo=new ProcessStartInfo(app2Launch);
74
75 pInfo.WindowStyle=ProcessWindowStyle.Normal;
76
77 Process p=Process.Start(pInfo);
78
79 }
80
81 }
82
83
84
85 void timeElapsed(object sender, ElapsedEventArgs args)
86
87 {
88
89 DateTime currTime=DateTime.Now;
90
91 foreach(DataRow dRow in ds.Tables["task"].Rows)
92
93 {
94
95 DateTime runTime=Convert.ToDateTime(dRow["time"]);
96
97 string formatString="MM/dd/yyyy HH:mm";
98
99 if(runTime.ToString(formatString)==currTime.ToString(formatString))
100
101 {
102
103 string exePath=dRow["exePath"].ToString();
104
105 AppLauncher launcher=new AppLauncher(exePath);
106
107 new Thread(new ThreadStart(launcher.runApp)).Start();
108
109 // Update the next run time
110
111 string strInterval=dRow["repeat"].ToString().ToUpper();
112
113 switch(strInterval)
114
115 {
116
117 case "D":
118
119 runTime=runTime.AddDays(1);
120
121 break;
122
123 case "W":
124
125 runTime=runTime.AddDays(7);
126
127 break;
128
129 case "M":
130
131 runTime=runTime.AddMonths(1);
132
133 break;
134
135 }
136
137 dRow["time"]=runTime.ToString(formatString);
138
139 ds.AcceptChanges();
140
141 StreamWriter sWrite=new StreamWriter(configPath);
142
143 XmlTextWriter xWrite=new XmlTextWriter(sWrite);
144
145 ds.WriteXml(xWrite, XmlWriteMode.WriteSchema);
146
147 xWrite.Close();
148
149 }
150
151 }
152
153 }
154
155
156
157 public AppScheduler()
158
159 {
160
161 // This call is required by the Windows.Forms Component Designer.
162
163 InitializeComponent();
164
165
166
167 // TODO: Add any initialization after the InitComponent call
168
169 }
170
171
172
173 // The main entry point for the process
174
175 static void Main()
176
177 {
178
179 System.ServiceProcess.ServiceBase[] ServicesToRun;
180
181
182
183 // More than one user Service may run within the same process. To add
184
185 // another service to this process, change the following line to
186
187 // create a second service object. For example,
188
189 //
190
191 // ServicesToRun = new System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
192
193 //
194
195 ServicesToRun = new System.ServiceProcess.ServiceBase[] { new AppScheduler() };
196
197
198
199 System.ServiceProcess.ServiceBase.Run(ServicesToRun);
200
201 }
202
203
204
205 /**//// <summary>
206
207 /// Required method for Designer support - do not modify
208
209 /// the contents of this method with the code editor.
210
211 /// </summary>
212
213 private void InitializeComponent()
214
215 {
216
217 //
218
219 // AppScheduler
220
221 //
222
223 this.CanPauseAndContinue = true;
224
225 this.ServiceName = "Application Scheduler";
226
227
228
229 }
230
231
232
233 /**//// <summary>
234
235 /// Clean up any resources being used.
236
237 /// </summary>
238
239 protected override void Dispose( bool disposing )
240
241 {
242
243 if( disposing )
244
245 {
246
247 if (components != null)
248
249 {
250
251 components.Dispose();
252
253 }
254
255 }
256
257 base.Dispose( disposing );
258
259 }
260
261
262
263 /**//// <summary>
264
265 /// Set things in motion so your service can do its work.
266
267 /// </summary>
268
269 protected override void OnStart(string[] args)
270
271 {
272
273 // TODO: Add code here to start your service.
274
275 configPath=ConfigurationSettings.AppSettings["configpath"];
276
277 try
278
279 {
280
281 XmlTextReader xRead=new XmlTextReader(configPath);
282
283 XmlValidatingReader xvRead=new XmlValidatingReader(xRead);
284
285 xvRead.ValidationType=ValidationType.DTD;
286
287 ds.ReadXml(xvRead);
288
289 xvRead.Close();
290
291 xRead.Close();
292
293 }
294
295 catch(Exception)
296
297 {
298
299 ServiceController srvcController=new ServiceController(ServiceName);
300
301 srvcController.Stop();
302
303 }
304
305 _timer.Interval=30000;
306
307 _timer.Elapsed+=new ElapsedEventHandler(timeElapsed);
308
309 _timer.Start();
310
311 }
312
313
314
315 /**//// <summary>
316
317 /// Stop this service.
318
319 /// </summary>
320
321 protected override void OnStop()
322
323 {
324
325 // TODO: Add code here to perform any tear-down necessary to stop your service.
326
327 }
328
329 }
330
331}
332
333
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
1
class
AppLauncher
2
3
{
4
5 string app2Launch;
6
7 public AppLauncher(string path)
8
9 {
10
11 app2Launch=path;
12
13 }
14
15 public void runApp()
16
17 {
18
19 ProcessStartInfo pInfo=new ProcessStartInfo(app2Launch);
20
21 pInfo.WindowStyle=ProcessWindowStyle.Normal;
22
23 Process p=Process.Start(pInfo);
24
25 }
26
27}
28
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
1
void
timeElapsed(
object
sender, ElapsedEventArgs args)
2
3
{
4
5 DateTime currTime=DateTime.Now;
6
7 foreach(DataRow dRow in ds.Tables["task"].Rows)
8
9 {
10
11 DateTime runTime=Convert.ToDateTime(dRow["time"]);
12
13 string formatString="MM/dd/yyyy HH:mm";
14
15 if(runTime.ToString(formatString)==currTime.ToString(formatString))
16
17 {
18
19 string exePath=dRow["exePath"].ToString();
20
21 AppLauncher launcher=new AppLauncher(exePath);
22
23 new Thread(new ThreadStart(launcher.runApp)).Start();
24
25 // Update the next run time
26
27 string strInterval=dRow["repeat"].ToString().ToUpper();
28
29 switch(strInterval)
30
31 {
32
33 case "D":
34
35 runTime=runTime.AddDays(1);
36
37 break;
38
39 case "W":
40
41 runTime=runTime.AddDays(7);
42
43 break;
44
45 case "M":
46
47 runTime=runTime.AddMonths(1);
48
49 break;
50
51 }
52
53 dRow["time"]=runTime.ToString(formatString);
54
55 ds.AcceptChanges();
56
57 StreamWriter sWrite=new StreamWriter(configPath);
58
59 XmlTextWriter xWrite=new XmlTextWriter(sWrite);
60
61 ds.WriteXml(xWrite, XmlWriteMode.WriteSchema);
62
63 xWrite.Close();
64
65 }
66
67 }
68
69}
70
71
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
1
<?
xml version
=
"
1.0
"
encoding
=
"
utf-8
"
?>
2
3
<!
DOCTYPE appSchedule[
4
5
<!
ELEMENT appSchedule (task
*
)
>
6
7
<!
ELEMENT task EMPTY
>
8
9
<!
ATTLIST task name CDATA #REQUIRED
>
10
11
<!
ATTLIST task exePath CDATA #REQUIRED
>
12
13
<!
ATTLIST task time CDATA #REQUIRED
>
14
15
<!
ATTLIST task repeat (D
|
W
|
M) #REQUIRED
>
16
17
]
>
18
19
<
appSchedule
>
20
21
<
task name
=
"
Notepad
"
exePath
=
"
%SystemRoot%\system32\notepad.exe
"
time
=
"
05/05/2006 10:45
"
repeat
=
"
D
"
/>
22
23
<
task name
=
"
Wordpad
"
exePath
=
"
C:\Program Files\Outlook Express\msimn.exe
"
time
=
"
05/05/2006 10:46
"
repeat
=
"
W
"
/>
24
25
<
task name
=
"
Calculator
"
exePath
=
"
%SystemRoot%\System32\calc.exe
"
time
=
"
05/05/2006 10:47
"
repeat
=
"
M
"
/>
26
27
</
appSchedule
>
28
29
Starting the service
1
protected
override
void
OnStart(
string
[] args)
2
3
{
4
5 // TODO: Add code here to start your service.
6
7 configPath=ConfigurationSettings.AppSettings["configpath"];
8
9 try
10
11 {
12
13 XmlTextReader xRead=new XmlTextReader(configPath);
14
15 XmlValidatingReader xvRead=new XmlValidatingReader(xRead);
16
17 xvRead.ValidationType=ValidationType.DTD;
18
19 ds.ReadXml(xvRead);
20
21 xvRead.Close();
22
23 xRead.Close();
24
25 }
26
27 catch(Exception)
28
29 {
30
31 ServiceController srvcController=new ServiceController(ServiceName);
32
33 srvcController.Stop();
34
35 }
36
37 _timer.Interval=30000;
38
39 _timer.Elapsed+=new ElapsedEventHandler(timeElapsed);
40
41 _timer.Start();
42
43}
44
45
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.