Table of Contents:
- Timer Objects in Windows Services with C#.NET
- Setting up the Project
- Adding Code
- Coding the Windows Service Start and Stop Event Handlers
- Building and Installing the Service
-
Timer Objects in Windows Services with C#.NET - Setting up the Project
(Page 2 of 5 )
1. Create a C# Windows Service project and name it TimerSrv.
The project will come with a class, Service1.cs. Double-click Service1.csin the project explorer to reveal the properties. Name the serviceTimerSrv and in the ServiceName field also fill in TimerSrv.2. Next we are going to add an installer to the project. Click on the hyperlink Add Installer. A design screen will be added to the project with 2 controls: serviceProcessInstaller1 and ServiceInstaller1.
3. Click the serviceProcessInstaller1 control and, in the properties dialog, change the account toLocalSystem.
4. In the serviceInstaller control, change the start type to Automatic, and give it a nice display name, like Timer Service.
Timer Objects in Windows Services with C#.NET - Adding Code
(Page 3 of 5 )
1. Switch to the code view of the Service1.cs file.
Note: we renamed the service to TimerSrv, so we need to change the Run command in the Main method of this class. Find the following line:
ServicesToRun = new System.ServiceProcess.ServiceBase[]
{ new Service1() };Now, change this to the following:
ServicesToRun = new System.ServiceProcess.ServiceBase[]
{ new TimerSrv() };2. In the top of the file add use statements:
Use System.IO;
// we need this to write to the file
use System.Timers;
//we need this to create the timer.3. Somewhere in the class, add a new private void AddToFile() method. We will use this to write text to a file.
private void AddToFile(string contents)
{//set up a filestream
FileStream fs = new
FileStream(@”c:/timerserv.txt”,FileMode.OpenOrCreate, FileAccess.Write);
//set up a streamwriter for adding text
StreamWriter sw = new StreamWriter(fs);
//find the end of the underlying filestream
sw.BaseStream.Seek(0, SeekOrigin.End);
//add the text
sw.WriteLine(contents);
//add the text to the underlying filestreamsw.Flush();
//close the writer
sw.Close();
}Now we can start coding the events.
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 andOnStop 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 OnStopmethod looks like this:
protected override void OnStop()
{
timer.Enabled = false;
AddToFile(“stopping service”);
}That’s all the coding we need to do!
Timer Objects in Windows Services with C#.NET - Building and Installing the Service
(Page 5 of 5 )
Build the executable: Build->Build Solution
In order to install the service we need to use the installutil console command, which comes with the .NET Framework.
Open a command line window by going to Start -> Programs -> Microsoft Visual Studio.Net -> Visual Studio.Net Tools -> Visual Studio.Net Command Prompt, and change to the directory where the executable is located. Enter the following command:
installutil TimerServ.exe
// Whatever you defined the executable
// name to be.Now the service is installed. To start and stop the service, go to Control Panel -> Administrative Tools -> Services. Right click the service and select Start.
Now the service is started, and you will be able to see entries in the log file we defined in the code.
Conclusion
Creating a timer, using a Windows Service, with Visual Studio.Net is not such a difficult task. This article showed the entire process of creating a timer object and using a Windows Service as the control vehicle.