October 24, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Using Timers in a Windows Service

  • April 5, 2004
  • By Mark Strawmyer
  • Send Email »
  • More Articles »

Windows Service Sample Code

Now, we'll create our service. The service will create a number of threads and execute the StartTimer method of the TimerItem on each thread. We'll add an event log instance to record the start of the service and the timer events.

using System;using System.Collections;using System.ComponentModel;using System.Data;using System.Diagnostics;using System.ServiceProcess;using System.Threading;namespace CodeGuru.TimerService{   public class TimerService : System.ServiceProcess.ServiceBase   {      private System.Diagnostics.EventLog _AppEventLog;      private Thread[] _WorkerThreads;      private TimedItem[] _Timers;      /// <summary>      /// Required designer variable.      /// </summary>      private System.ComponentModel.Container components = null;      public TimerService()      {         // This call is required by the Windows.Forms Component         // Designer.         InitializeComponent();         // TODO: Add any initialization after the InitComponent         // call      }      // The main entry point for the process      static void Main()      {         System.ServiceProcess.ServiceBase[] ServicesToRun;         ServicesToRun = new System.ServiceProcess.ServiceBase[] {             new TimerService() };         System.ServiceProcess.ServiceBase.Run(ServicesToRun);      }      /// <summary>      /// Required method for Designer support - do not modify      /// the contents of this method with the code editor.      /// </summary>      private void InitializeComponent()      {         this._AppEventLog = new System.Diagnostics.EventLog();            ((System.ComponentModel.ISupportInitialize)             (this._AppEventLog)).BeginInit();         //         // _AppEventLog         //         this._AppEventLog.Log = "Application";         this._AppEventLog.Source = "TimerService";         //         // TimerService         //         this.ServiceName = "TimerService";            ((System.ComponentModel.ISupportInitialize)             (this._AppEventLog)).EndInit();      }      /// <summary>      /// Clean up any resources being used.      /// </summary>      protected override void Dispose( bool disposing )      {         if( disposing )         {            if (components != null)            {               components.Dispose();            }         }         base.Dispose( disposing );      }      /// <summary>      /// Set things in motion so your service can do its work.      /// </summary>      protected override void OnStart(string[] args)      {         this._Timers = new TimedItem[5];         _WorkerThreads = new Thread[5];         for( int i = 0; i < 5; i++ )         {            _Timers[i] = new TimedItem(this._AppEventLog);            _Timers[i].Name = "Timer #" + i.ToString();            _WorkerThreads[i] = new Thread(new               System.Threading.ThreadStart(_Timers[i].StartTimer));            _WorkerThreads[i].Start();         }      }      /// <summary>      /// Stop this service.      /// </summary>      protected override void OnStop()      {         for( int i = 0; i < 5; i++ )         {            _Timers[i].StopTimer();         }      }   }}

Windows Service Installer Sample Code

Now, we include the installer to control the installation of the service. If you have any problems getting this to install using the InstallUtil.exe, make sure you are using the InstallUtil.exe for the appropriate version of the .NET Framework you are using. If you have the 1.0 and 1.1 framework installed, there is a chance the InstallUtil.exe will point to the wrong version of the framework; this will result in an error when you try to install your 1.1-based Windows Service.

using System;using System.Collections;using System.ComponentModel;using System.Configuration.Install;namespace CodeGuru.TimerService{   /// <summary>   /// Summary description for ProjectInstaller.   /// </summary>   [RunInstaller(true)]   public class ProjectInstaller : System.Configuration.Install.Installer   {      private System.ServiceProcess.ServiceProcessInstaller         _TimerServiceProcessInstaller;      private System.ServiceProcess.ServiceInstaller _TimerServiceInstaller;      /// <summary>      /// Required designer variable.      /// </summary>      private System.ComponentModel.Container components = null;      public ProjectInstaller()      {         // This call is required by the Designer.         InitializeComponent();         // TODO: Add any initialization after the         // InitializeComponent call      }      /// <summary>      /// Clean up any resources being used.      /// </summary>      protected override void Dispose( bool disposing )      {         if( disposing )         {            if(components != null)            {               components.Dispose();            }         }         base.Dispose( disposing );      }      #region Component Designer generated code      /// <summary>      /// Required method for Designer support - do not modify      /// the contents of this method with the code editor.      /// </summary>      private void InitializeComponent()      {         this._TimerServiceProcessInstaller = new         System.ServiceProcess.ServiceProcessInstaller();         this._TimerServiceInstaller = new         System.ServiceProcess.ServiceInstaller();         //         // _TimerServiceProcessInstaller         //         this._TimerServiceProcessInstaller.Account =            System.ServiceProcess.ServiceAccount.LocalSystem;         this._TimerServiceProcessInstaller.Password = null;         this._TimerServiceProcessInstaller.Username = null;         //         // _TimerServiceInstaller         //         this._TimerServiceInstaller.ServiceName = "TimerService";         this._TimerServiceInstaller.StartType =            System.ServiceProcess.ServiceStartMode.Automatic;         //         // ProjectInstaller         //         this.Installers.AddRange(new            System.Configuration.Install.Installer[] {            this._TimerServiceInstaller,            this._TimerServiceProcessInstaller});      }      #endregion   }}

Possible Enhancements

Now you have seen a few ways in which timers can be used in a Windows Service application. Hopefully, those of you who contacted me with questions about how to use a timer in a service application will find this helpful. A few enhancements you can consider to make this more useful for yourself are as follows:

  • Add a configuration file to the application and include the number of threads to create as a configurable item.
  • Change the polling interval to be randomly generated for each thread. This will ensure that each thread is not taking action at the same time.
  • Create an event log dedicated to the application. This will prevent the Application log from becoming overly cluttered with entries as you execute the application.

Future Columns

The topic of the next column is yet to be determined. If you have something in particular that you would like to see explained here, you could reach me at mstrawmyer@crowechizek.com.

About the Author

Mark Strawmyer, MCSD, MCSE, MCDBA is a Senior Architect of .NET applications for large and mid-size organizations. Mark is a technology leader with Crowe Chizek in Indianapolis, Indiana. He specializes in the architecture, design, and development of Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for application development with C#. You can reach Mark at mstrawmyer@crowechizek.com.





Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel