Articles → .NET WINDOWS SERVICE → Adding Timer Control in windows service

Adding Timer Control in windows service



  1. Software Requirement
  2. Prerequisite Knowledge
  3. Creation of a new project
  4. Add a timer control
  5. Set the timer’s interval
  6. Enable the timer control
  7. Add an elapsed event for timer control
  8. Adding the code in elapsed event
  9. Install and start service
  10. Output

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