title: Using System.Timers.Timer in asp.net
body: <p>I use the following code in a asp.net website.</p>
  
  <p>On application init i call InitializeTimer() once.</p>
  
  <p>The goal of the code was to run DoWork() once every hour (1 time per hour) .</p>
  
  <p>I also wanted the code to execute on different time every loop so i added the random part.</p>
  
  <p><strong>The result i got was werid , i can not find a explaination why is happens</strong>.</p>
  
  <p>The code executed the function after 2hrs , then again after 2hrs , then after <strong>3hrs</strong> , then after 2hrs , and 2hrs again.****</p>
  
  <p><strong>Can anybody explain the reason?</strong></p>
  
  <pre><code>using System.Timers;
  ....
  private static random = new Random();
  ....
  public static void InitializeTimer()
  {
      tTimer = new Timer();
      tTimer.AutoReset = true;
      tTimer.Interval = TimeSpan.FromHours(1.0).TotalMilliseconds;
      tTimer.Elapsed += new ElapsedEventHandler(ClassName1.tMailer_Elapsed);
      tTimer.Start();
  }
  
  private static void tTimer_Elapsed(object sender, ElapsedEventArgs e)
  {
      tTimer.Interval += random.Next(-5, 5);
  
      DoWork();
  }
  </code></pre>
  
  <p><strong>Update:</strong></p>
  
  <ol>
  <li><p><strong>Please don't post "use windows service" , or "scheduled task".
  My question is for the following code</strong> I'm not looking for better alternatives.
  Also , during this test (10hrs) , website was with high traffic , iis pool did not restart!</p></li>
  <li><p>Based on the following MSDN: (<a href="http://msdn.microsoft.com/en-us/library/system.timers.timer.interval.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.timers.timer.interval.aspx</a>)</p></li>
  </ol>
  
  <blockquote>
    <p>If the interval is set after the Timer
    has started, the count is reset. For
    example, if you set the interval to 5
    seconds and then set the Enabled
    property to true, the count starts at
    the time Enabled is set. If you reset
    the interval to 10 seconds when count
    is 3 seconds, the Elapsed event is
    raised for the first time 13 seconds
    after Enabled was set to true.</p>
  </blockquote>
  
  <p>Is it possible that re-setting the interval in the elapsed function is the cause of the problem?</p>
  
  <p>Meaning that when tTimer_Elapsed function is called the count is 1hr(min a few millisecond)
  and my code "tTimer.Interval += random.Next(-5, 5);" is adding another full hour to the Interval?</p>