Wednesday, October 30, 2013

Setting Timer for a Windows Service

A windows service is supposed to perform a set of operation repeated after a pre-defined interval of time. For the service to trigger the operation after a pre-defined interval we need to define a timer and call the implementation method when the timer elapses.

We will create a times and define the interval when the service gets started, there after whenever a time elapses the timers Elapsed event gets triggered, we can bind our implementation method to this event so that the method gets called every time the time elapses.

We will use the same windows service which we created in the post Creating a Basic Windows Service
 and add a timer to the service.
We need to define the interval for the service, we shall do this by adding a config file and adding the interval in the config file, so that it can be changed without re-building the solution. Add a config file App.config to the project and add the following tire key to the config file.

xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="timer_interval" value="2000"/>
  </appSettings>
</configuration>

Now we shall, get the interval defined in the config file and set it to the timer.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Configuration;

namespace NotificationService
{
    public partial class NotificationService : ServiceBase
    {
        #region Variable Declaration
        Timer serviceTimer;
        Double timer_interval;
        #endregion
       
        public NotificationService()
        {
            InitializeComponent();
        }
        //
        protected override void OnStart(string[] args)
        {
            if (double.TryParse(ConfigurationManager.AppSettings["timer_interval"], out timer_interval))
            {
                serviceTimer = new Timer(timer_interval);
                serviceTimer.Elapsed += CheckErrorNotifications;
                serviceTimer.Start();
            }
            else
            {
                //Conversion to Double failed, Log error here
            }
        }
        //
        private void CheckErrorNotifications(object sender, ElapsedEventArgs args)
        {
        }
        //
        protected override void OnStop()
        {
        }
    }
}


Add a reference to the System.configuration assembly since we are using this assembly to read the key values from the config file.

Search Flipkart Products:
Flipkart.com

No comments: