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
Click to Enlarge
Add A Timer Control
Click to Enlarge
- Right-click on the toolbar and click on "Choose Items…".
- A popup window comes. From the window, choose the timer option as shown in figure below.
Click to Enlarge
- Click Ok.
Set The Timer’S Interval
- Click on the timer control and press F4.
- A property window appears. Set the Interval property to 10000.
Click to Enlarge
Enable The Timer Control
- Enable the timer control at the design time
- Click on the timer control
- Press F4
- Set the Enabled property to true.
- 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
- Click on the timer control and press F4.
- Property window appears. Click on the thunder like icon in the yellow color as shown in figure below
Click to Enlarge
- 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
- Build the application.
- Add the installer
- Build again the application
- Install service using the "installUtil".
- Start the service.
Output
Click to Enlarge