posted by Will Senn on Mon 5th Jan 2004 19:35 UTC

"Windows .NET Services, Page 4"

6. Create a Timer

In this step we will create a 30 second timer with the idea that our service will do something every 30 seconds.

a. Click back to the timedService.cs [Design] window.
b. Click the Toolbox, if you cannot see the Toolbox anywhere, click the menu item: View - Toolbox and you may as well click the Push Pin icon in the top right of the window, so it will stay in the foreground.
c. Click the Components* button
d. Double Click the Timer* button (icon that looks like a clock). A timer icon will now appear in the design window.



e. Click the Toolbox's push pin so it will keep itself out of the way.
f. Click the timer1 icon in the design window and switch to the Properties Window and timer1 System.Timers.Timer should be selected.
g. Verify that the Enabled property is True or change it to True
h. Change the Interval property to 30000 (30 seconds times 1000 milliseconds)
i. Change the (Name) property to something like timer.




We are set to make the service do something useful.

*If either the Components or Timer buttons are not present, right click in the grey area and select Add/Remove Items...



a dialog will pop up and you can select Timer - System.Timers from the .NET Framework Components tab.




7. Do Something Useful

This is the sticky wicket, or is it thicket? What is useful? In our case, we will have our application log a message to a text file, saying that the program is alive and well. This will provide us with a simple, yet effective demonstration the efficacy of our service.

a. Click back to the timedService.cs [Design] window.
b. Double Click the timer icon. This will drop you into the timedService.cs code window and create a method called timer_Elapsed. This is where we will add our logging code.
c. Type (or copy and paste) the code below into the method, between the start and end curly braces:
	System.IO.StreamWriter logfile = System.IO.File.AppendText("c:\\log.txt");
	logfile.WriteLine("[" + System.DateTime.Now + "]: I am ALIVE!");
	logfile.Close();
This is the only coding that we will do, period. The timer_Elapsed method is where you will want to call your class methods for doing the work. Obviously, you can elaborate on this section to your hearts content.

Table of contents
  1. "Windows .NET Services, Page 1"
  2. "Windows .NET Services, Page 2"
  3. "Windows .NET Services, Page 3"
  4. "Windows .NET Services, Page 4"
  5. "Windows .NET Services, Page 5"
e p (0)    31 Comment(s)