title: Windows service scheduled execution
body: <p>If I have a Windows Service that needs to execute a task every 30 seconds which is better to use; the Timer() class or a loop that executes the task then sleeps for a number of seconds?</p>
  
  <pre><code>class MessageReceiver 
  {
      public MessageReceiver()
      {
      }
  
      public void CommencePolling()
      {
          while (true)
          {
              try 
              {
                  this.ExecuteTask();     
                  System.Threading.Thread.Sleep(30000);
              }
              catch (Exception)
              {
                  // log the exception
              }
          }
      }
  
      public void ExecutedTask()
      {
          // do stuff
      }
  }
  
  class MessageReceiver 
  {
      public MessageReceiver()
      {
      }
  
      public void CommencePolling()
      {
          var timer = new Timer()
              {
                  AutoReset = true,
                  Interval = 30000,
                  Enabled = true
              };
  
          timer.Elapsed += Timer_Tick;    
      }
  
      public void Timer_Tick(object sender, ElapsedEventArgs args)
      {
          try 
          {
              // do stuff
          }
          catch (Exception)
          {
              // log the exception
          }
      }
  }
  </code></pre>
  
  <p>The windows service will create an instance of the MessageReciever class and execute the CommencePolling method on a new thread.</p>