Articles → .NET WINDOWS SERVICE → Adding Timer Control In Windows Service

Adding Timer Control In Windows Service






Software Requirement





Prerequisite Knowledge





Creation Of A New Project




Picture showing the project explorer of windows service project
Click to Enlarge


Add A Timer Control




Picture showing the timer control in design mode
Click to Enlarge



  1. Right-click on the toolbar and click on "Choose Items…".
  2. A popup window comes. From the window, choose the timer option as shown in figure below.


  3. Picture showing a list of components from which timer component is selected
    Click to Enlarge

  4. Click Ok.



Set The Timer’S Interval


  1. Click on the timer control and press F4.
  2. A property window appears. Set the Interval property to 10000.
Picture showing the property window to set the time interval of the timer
Click to Enlarge








Enable The Timer Control


  1. Enable the timer control at the design time
    1. Click on the timer control
    2. Press F4
    3. Set the Enabled property to true.
  2. Enable the timer control at run time – To do that, write the following code on OnStart event
protected override void OnStart(string[] args) {
	timer1.Enabled = true;
}



Add An Elapsed Event For Timer Control


  1. Click on the timer control and press F4.
  2. Property window appears. Click on the thunder like icon in the yellow color as shown in figure below


  3. Picture showing property window to select Elapsed event of the timer
    Click to Enlarge

  4. Double-click on the area as shown in the figure above. Following code will be added in the code behind
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {

}



Adding The Code In Elapsed Event


private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
	DirectoryInfo dir = new DirectoryInfo(@"c:\karan");
	if (dir.GetFiles().Count() < 10) {
		File.Create(string.Format(@"c:\karan\{0}.txt", System.Guid.NewGuid()));
	}
}







Install And Start Service


  1. Build the application.
  2. Add the installer
  3. Build again the application
  4. Install service using the "installUtil".
  5. Start the service.

Output




Picture showing the output of the windows service
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Tuesday, August 21, 2012

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250