Menu ▼


Run windows service using timer control

When the service need to run continuously in specific time interval, then we have to use timer control. In this example we will take a timer control and set the timer value 5 seconds. then the service will write a record in the log for every 5 seconds.

Code:
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.IO;

namespace WindowsServiceExample
{
    public partial class Service1 : ServiceBase
    {

        System.Timers.Timer serviceTimer = null;
        string fileLocation = "C:\\servicelog.txt";

        public Service1()
        {
            InitializeComponent();
            serviceTimer = new System.Timers.Timer();
            serviceTimer.Elapsed += new System.Timers.ElapsedEventHandler(serviceTimer_Elapsed);
            serviceTimer.Interval = 5 * 1000;
            serviceTimer.Enabled = true;
            serviceTimer.Start();
        }
        protected override void OnStart(string[] args)
        {
            
            if (!File.Exists(fileLocation))
                File.Create(fileLocation).Close();
            File.AppendAllText(fileLocation, "Service started : " + DateTime.Now.ToString() + Environment.NewLine);            
        }

        void serviceTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            File.AppendAllText(fileLocation, "Service running at : " + DateTime.Now.ToString() + Environment.NewLine);
        }

        protected override void OnStop()
        {
            serviceTimer.Stop();
            serviceTimer.Enabled = false;
            File.AppendAllText(fileLocation, "Service stoped : " + DateTime.Now.ToString() + Environment.NewLine);
        }
    }
}

Output:





comments powered by Disqus


Search dotnetlearners.com