pavanarya

Let us share the knowledge

Windows Services and using Timers in Windows Services To Run specific Tasks at Regular Intervals

with one comment

Hi,
In this post i wan to write about windows services and how to use timers with windows services to execute specific tasks at regular interval.

Coming to windows services it is nothing but they are long running exe’s which performs certain tasks without user intervention.They can be started at the time of windows boot up and also users can either start or stop or pause these windows services using windows task manager.

The path for Windows Task manager is click on start button—-> Right click on My Computer—->Click on Manage—->Click on Services—-> Here we can see list of process in different states.

Life Time Of A Windows Service

Windows services undergo several intermediate states. Initially the service should be installed. Once the service is installed then it should be started using Windows task manager.

Initially after installing the service we should start the service using Service Control Manager(Windows Task Manager).
Once the application is started it will execute onStart() and it will be in running state. Then we can change that to either continue(onContinue()),Pause(onPause()) or stop(onStop()) the service. At a time a windows service can be only in 1 state.

Creating Windows Services using Visual Studio

1.Create a new project in visual studio by selecting the Create Empty application and name the application as MyFirstWindowsService.

2.Now add a class file and name it as MyFirstWindowsService. Now we will have a file called MyFirstWindowsService.cs which will be used for creating windows services.

3.In order to create a windows services our class should inherit the class System.ServiceProcess.ServiceBase.
In order to inherit the class ServiceBase we should add a dll reference of System.ServiceProcess to our project

ServiceBase class is the root class for creating windows services.So in our service we should extend the ServiceBase class and override methods present in the class Servicebase like onStart(),onPause(),onStop() and write our custom code in that.

Now let us see the skeleton of the root file(Service1.cs) which contains all the information and methods related to the service.

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 MyFirstWindowsService
{
    public partial class MyFirstWindowsService: ServiceBase
    {
        public MyFirstWindowsService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
        }

        protected override void OnStop()
        {
        }
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

      

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            components = new System.ComponentModel.Container();
            this.ServiceName = "Service1";
        }

    }
}

Now we are done with creating a windows service that do’s nothing(an empty service). That is we are done with basic logic of windows service.

Now we are supposed to add a main method which is the entry point for all the services that were created.
Inside the main method we will create an array of object for the services created. Then we will call the static method Run() method of System.ServiceProcess.ServiceBase class which actually calls the onStart() method present in the service.

 static void Main()
        {
            ServiceBase[] ServicesToRun;
           Debugger.Break();
            ServicesToRun = new ServiceBase[] 
			{ 
				new MyFirstWindowsService() 
			};
            ServiceBase.Run(ServicesToRun);
        }

Now we are done with the basic cooking of the windows service. Now we can add salt and pepper to our code. Now i am going to add timers so that the service will execute specific tasks at regular intervals.

So create a timer class
System.Timers.Timer timer = new System.Timers.Timer();
and inside the constructor add some properties like

System.Timers.Timer timer = new System.Timers.Timer();
 public MyFirstWindowsService()
        {
            InitializeComponent();
            this.CanStop = true;
            this.CanPauseAndContinue = true;
            
        }

once the service is started we can schedule the timer and once the timer is elapsed we can execute the some function.
So inside the onStart() we can add the following code.

 protected override void OnStart(string[] args)
        {
            timer.Enabled = true;
            timer.Interval = 10000;
            timer.Elapsed += new    System.Timers.ElapsedEventHandler(timer_Elapsed);
        }

So initially we are enabling the timer and then we are setting some time interval. once the interval is elapsed we can call the event timer.Elapsed which will execute the method specified.


        protected void timer_Elapsed(object source, System.Timers.ElapsedEventArgs aa)
        {

           //Here we can write beautiful code that performs some our own tasks.
        }
        

Now we are done with the timers in the service so our timer_Elapsed() will be executed at a regular intrval of 10000 milliseconds.

Adding Installer to Install our service in Service control manager

1.Right click on the service file and click on View Designer.
2. Now right click on the file and click on Add Installer.

A new class, ProjectInstaller, and components that is ServiceProcessInstaller and ServiceInstaller, are added to your project, and property values for the service are copied to the components.

Now we are all set for the installation of the windows service in our service controller manager.

Installing Windows Service

1.Build the entire solution and a new exe file is generated in the debug folder.
2.Now open the visual studio command prompt.
3. Use the command InstallUtil to install the service in the SCM.

Now the service is installed we can we verify that in our windows service manager. WE should find an entry in the services list(with the same name of the dll). Now right click on it and click on start.

Now our service is successfully started and it executes our timer_elapsed() method at regular intervals of 10000milliseconds.

Debugging a Windows Service

Here we can see how to debug a windows servcie

About these ads

Written by pavanarya

January 30, 2012 at 9:14 am

Posted in c#

One Response

Subscribe to comments with RSS.

  1. [...] in my previous post about windows service and installing windows services in the windows task [...]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 67 other followers

%d bloggers like this: