Writing Windows Services in C#

What follows is a skeleton Windows service application written in C#, which you can use as a framework for developing your own services. It is based on Writing a Useful Windows Service in .NET in Five Minutes by Dave Fetterman, with a few changes to make it simpler, and to bring it up to date.

To start, here is the service class.

using System;
using System.ServiceProcess;
using System.Threading;
 
public class CronService : ServiceBase
{
   private CronJob job;
   private Timer stateTimer;
   private TimerCallback timerDelegate;
 
   public CronService()
   {
      this.ServiceName = "Cron";
      this.CanStop = true;
      this.CanPauseAndContinue = false;
      this.AutoLog = true;
   }
 
   protected override void OnStart(string [] args)
   {
      job = new CronJob();
      timerDelegate = new TimerCallback(job.DoSomething);
      stateTimer = new Timer(timerDelegate, null, 1000, 1000);
   }
 
   protected override void OnStop()
   {
      stateTimer.Dispose();
   }
 
   public static void Main()
   {
      System.ServiceProcess.ServiceBase.Run(new CronService());
   }
}

This is the installer class. You will need to add a reference to System.Configuration.Install.dll.

using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
 
[RunInstaller(true)]
public class CronInstaller : Installer
{
   private ServiceProcessInstaller processInstaller;
   private ServiceInstaller serviceInstaller;
   public CronInstaller()
   {
       processInstaller = new ServiceProcessInstaller();
       serviceInstaller = new ServiceInstaller();
       processInstaller.Account = ServiceAccount.LocalSystem;
       serviceInstaller.StartType = ServiceStartMode.Manual;
       serviceInstaller.ServiceName = "Cron";
       Installers.Add(serviceInstaller);
       Installers.Add(processInstaller);
   } 
}

The new service must be installed before it can be run. Open a .NET command prompt and do this:

C:\> InstallUtil /LogToConsole=true cron.exe   # flag is optional but handy
C:\> net start cron
C:\> net stop cron              # to stop the service when finished
C:\> InstallUtil /u cron.exe    # to uninstall

That's it! Thanks again to Dave Fetterman for providing the original example.

Did you enjoy this article?

Help me write more like it. »

This came in handy, thankyou.

Exactly what I needed.

Cheers