HomeC# Timer Objects in Windows Services with C#....
Timer Objects in Windows Services with C#.NET
Timer events can be very useful when you need to run a routine on a regular basis. In .NET, creating Windows services with the timer object is very easy to do. In this article we are going to create a timer which writes text to a file on regular intervals, and we’ll employ a Windows Service to control the timer.
Contributed by Rogier Doekes Rating: / 232 October 18, 2004
From the timer object (in the System.Timers namespace) we use the following properties and events:
Elapsed: Everything in the timer evolves around the Elapsed event, which is the event that is raised every interval. You create code to be executed and call that code in the Elapsed event.
Interval: Used to set the time between raising the Elapsed event.
AutoReset: Ensures that the timer will be reset after every Elapse event. Therefore, if you would only like to execute the Elapse event once, you set the AutoReset property to false. When you omit the AutoReset property, it is assumed to be true.
Enabled: Used to tell the timer to start or stop.
Windows Service Concept
A Windows Service has very defined start and stop events. Starting and stopping timers using these events is very organized and is run as a background process. If you define the Windows Service to start automatically, you need not worry about starting the timer again; this background process will keep on running until you stop the service and disable it. Since this is a background process, there will not be a user interface to dialog with the user. In case of exceptions, messages would be written to the Windows Event Log.
Every Windows Service must have a Main method where you issue a Run command, which loads the service into the Services Control Manager. However, if you use Visual Studio.NET, all this code will be generated automatically.
1. Create a C# Windows Service project and name it TimerSrv.
The project will come with a class, Service1.cs. Double-click Service1.cs in the project explorer to reveal the properties. Name the service TimerSrv 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 to LocalSystem.
4. In the serviceInstaller control, change the start type to Automatic, and give it a nice display name, like Timer Service.
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:
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:
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.