Timer Objects in Windows Services with C#.NET - Coding the Windows Service Start and Stop Event Handlers
(Page 4 of 5 )
In the Service1.cs file we only need to write code for the OnStart and OnStop events. In the OnStart() void method, add the following line of code:
AddToFile(“Starting Service”);
Now, in the OnStop event add the following line:
AddToFile(“Stopping Service”);
This is all we need to do to have a working Windows Service. Next we’ll add the timer to the service.
Creating the Timer
Just under the class definition in the Service1.cs file, add the following global variables:
//Initialize the timer
Timer timer = new Timer();
The idea behind the timer is that it sleeps for a specified period (defined by the interval method), and then executes the code specified with the elapsed event. We need to define a method that will be executed when the Elapsed event occurs, and we do this with the following code, which adds a line of text to the file:
Private void OnElapsedTime(object source, ElapsedEventArgs e)
{
AddToFile(“ Another entry”);
}
Now we can setup the timer.
In the OnStart method we add code to reflect what to do when the elapsed event is raised. In this case, we need to invoke the OnElapsedTime method we defined above, set the interval (in milliseconds) the project needs to sleep, and enable the timer so it raises the Elapsed event.
The complete OnStart method looks like this:
protected override void OnStart(string[] args)
{
//add line to the file
AddToFile(“starting service”);
//ad 1: handle Elapsed event
timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
//ad 2: set interval to 1 minute (= 60,000 milliseconds)
timer.Interval = 60000;
//ad 3: enabling the timer
timer.Enabled = true;
}
The OnStop event also needs to be modified. A mere timer.Enabled = false suffices. The complete OnStop method looks like this:
protected override void OnStop()
{
timer.Enabled = false;
AddToFile(“stopping service”);
}
That’s all the coding we need to do!
Next: Building and Installing the Service >>
More C# Articles
More By Rogier Doekes
|
| · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | · | | | | |
|