title: Why is the timer not working in windows service?
body: <p>I know this is an already asked question, but I couldn't find any solution. Here is my service.</p>
  
  <pre><code>class Program : ServiceBase
  {
      private  Timer _timer;
      public Program()
      {
          ServiceName = "PrintTime";
      }
  
      static void Main(string[] args)
      {
          Run(new Program());
      }
  
      protected override void OnStart(string[] args)
      {
          base.OnStart(args);
          _timer = new Timer(5000);
          _timer.Elapsed += _timer_Elapsed;
          _timer.Start();
      }
  
      void _timer_Elapsed(object sender, ElapsedEventArgs e)
      {
          WriteTimeToFile();
      }
  
      protected override void OnStop()
      {
          _timer.Stop();
      }
  
      private void WriteTimeToFile()
      {
          using (FileStream fs = new FileStream(@"d:\mylog.txt", FileMode.Append,            FileAccess.ReadWrite))
          {
              StreamWriter streamWriter = new StreamWriter(fs);
              streamWriter.Write(DateTime.Now.ToShortTimeString());
              streamWriter.Close();
              fs.Close();
          }
      }
  
  }
  </code></pre>
  
  <p>As you can see I want to write <code>currentTime</code> into my <code>Mylog.txt</code> file every 5 seconds, but nothing happens after even 2 minutes. If I put the <code>WriteTimeToFile()</code> function into <code>OnStart</code> method it works fine, but not in a timer.</p>
  
  <p>Any help would be greatly appreciated.</p>