Create Window service project in C# - Part 3 (Using Timers in a service)

So now we know how to create, launch and view event log for a Windows service using C#. If you do not have a clear idea please refer following two posts.

 Now let's create a windows service application which use Timers. Because most of the windows services are running to execute specific task periodically. That's mean execute a code after specific time period without user interaction. 

For that purpose you can use Timer component in C# which enables you to execute a code segment periodically. Let's see how this thing worked...

First you have to create a timer object on your service class. I am not going to further describe these things, because you will be able to understand by looking on following 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;

namespace MyWinService
{
    public partial class MyService : ServiceBase
    {
        System.Timers.Timer tmrDelay;
        int count;

        public MyService()
        {
            InitializeComponent();

            if (!System.Diagnostics.EventLog.SourceExists("MyLogSrc"))
            {
                System.Diagnostics.EventLog.CreateEventSource("MyLogSrc", "MyLog");
            }

            //set our event log to system created log
            myEventLog.Source = "MyLogSrc";
            myEventLog.Log = "MyLog";

            tmrDelay = new System.Timers.Timer(5000);
            tmrDelay.Elapsed += new System.Timers.ElapsedEventHandler(tmrDelay_Elapsed);
        }

        void tmrDelay_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            string str = "Timer tick " + count;
            myEventLog.WriteEntry(str);
            count++;
        }

        protected override void OnStart(string[] args)
        {
            myEventLog.WriteEntry("MyService started");
            tmrDelay.Enabled = true;
        }

        protected override void OnStop()
        {
            myEventLog.WriteEntry("MyService stoped");
            tmrDelay.Enabled = false;
        }
    }
}

This code was placed on "Service1.cs" file on my project.

Code explained

 System.Timers.Timer tmrDelay;
 int count;
Declare timer variable for timing purpose and count variable for counting purpose.

 tmrDelay = new System.Timers.Timer(5000);
 tmrDelay.Elapsed += new System.Timers.ElapsedEventHandler(tmrDelay_Elapsed);
Create timerDelay object for 5000ms(5 seconds) delay. Then event handler so that timer will execute the code within the "tmrDelay_Elapsed" method in every five seconds. (Do not worry this event handler code line will automatically generate when you type '+=' and press tab)

 void tmrDelay_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 {
    string str = "Timer tick " + count;
    myEventLog.WriteEntry(str);
    count++;
 }
This is the event handler for timer elapsed event. When timer elapsed a specific 'interval' time it will execute code within this event handler.

Here adds a new entity on event logger as "Timer tick 1" , 2, 3, 4 ....

Other codes are as it is on previous post. Therefore I am not going to explain those here.


Now build and install your solution as describe in Part 1. Then you will see some thing similar to this in "Event Viewer" or "Visual Studio".


As you can see when each time timer elapsed it will add new entity to logger. So now it's your turn place any code in timer elapsed event to execute it periodically.

Complete project can be downloaded from here.

8 comments:

  1. Milinda Pro: Create Window Service Project In C - Part 3 (Using Timers In A Service) >>>>> Download Now

    >>>>> Download Full

    Milinda Pro: Create Window Service Project In C - Part 3 (Using Timers In A Service) >>>>> Download LINK

    >>>>> Download Now

    Milinda Pro: Create Window Service Project In C - Part 3 (Using Timers In A Service) >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete