title: C# midnight timer invoked prematurely
body: <p>My system needs to update its DB at midnight, every day.<br>
  The value is a daily usage counter.<br>
  In order to do so I've coded this class:</p>
  
  <pre><code>internal class MidnightTimer
  {
      internal event EventHandler Elapsed = delegate { };
      private Timer timer;
  
      internal MidnightTimer()
      {
          timer = new Timer();
          timer.Elapsed += timer_Elapsed;
      }
  
      internal void Start()
      {
          TimeSpan timeSpanToMidnight = GetNextMidnight().Subtract(DateTime.Now);
          timer.Interval = timeSpanToMidnight.TotalMilliseconds;
          timer.Start();
      }
  
      private void timer_Elapsed(object sender, ElapsedEventArgs e)
      {
          Elapsed(this, EventArgs.Empty);
          timer.Stop();
          Start();
      }
  
      private static DateTime GetNextMidnight()
      {
          const string datePattern = "dd/MM/yyyy hh:mm:ss";
          const string dateFormat = "{0:00}/{1:00}/{2:0000} {3:00}:{4:00}:{5:00}";
          DateTime nextMidnight;
  
          string dateString = string.Format(dateFormat, DateTime.Now.Day + 1, DateTime.Now.Month, DateTime.Now.Year, 0, 0, 0);
          bool valid = DateTime.TryParseExact(dateString, datePattern, CultureInfo.InvariantCulture, DateTimeStyles.None, out nextMidnight);
  
          if (!valid)
          {
              dateString = string.Format(dateFormat, 1, DateTime.Now.Month + 1, DateTime.Now.Year, 0, 0, 0);
              valid = DateTime.TryParseExact(dateString, datePattern, CultureInfo.InvariantCulture, DateTimeStyles.None, out nextMidnight);
          }
  
          if (!valid)
          {
              dateString = string.Format(dateFormat, 1, 1, DateTime.Now.Year + 1, 0, 0, 0);
              DateTime.TryParseExact(dateString, datePattern, CultureInfo.InvariantCulture, DateTimeStyles.None, out nextMidnight);
          }
  
          return nextMidnight;
      }
  }
  </code></pre>
  
  <p>The problem is that it is not accurate.<br>
  The event is sometimes invoked a few milliseconds before midnight, and because I'm resetting the value after it is sent to the DB in  the first event, it is resetting the value in the DB after the second event.</p>
  
  <p>Any help is appreciated.</p>