title: How can I raise an event every hour (or specific time interval each hour) in .NET?
body: <p>I'm working on a little web crawler that will run in the system tray and crawl a web site every hour on the hour.</p>
  
  <p>What is the best way to get .NET to raise an event every hour or some other interval to perform some task. For example I want to run an event every 20 minutes based on the time. The event would be raised at:</p>
  
  <pre><code>00:20
  00:40
  01:00
  01:20
  01:40
  </code></pre>
  
  <p>and so on. The best way I can think of to do this is by creating a loop on a thread, that constantly checks if the time is divisible by a given interval and raises a callback event if the time is reached. I feel like there has got to be a better way. </p>
  
  <p>I'd use a <code>Timer</code> but I'd prefer something that follows a "schedule" that runs on the hour or something along those lines. </p>
  
  <p>Without setting up my application in the windows task scheduler is this possible?</p>
  
  <p><strong>UPDATE:</strong><br>
  I'm adding my algorithm for calculating the time interval for a timer. This method takes a "<code>minute</code>" parameter, which is what time the timer should trigger a tick. For example, if the "<code>minute</code>" parameter is 20, then the timer will tick at the intervals in the timetable above.</p>
  
  <pre><code>int CalculateTimerInterval(int minute)
  {
      if (minute &lt;= 0)
          minute = 60;
      DateTime now = DateTime.Now;
  
      DateTime future = now.AddMinutes((minute - (now.Minute % minute))).AddSeconds(now.Second * -1).AddMilliseconds(now.Millisecond * -1);
  
      TimeSpan interval = future - now;
  
      return (int)interval.TotalMilliseconds;
  }
  </code></pre>
  
  <p>This code is used as follows:  </p>
  
  <pre><code>static System.Windows.Forms.Timer t;
  const int CHECK_INTERVAL = 20;
  
  
  static void Main()
  {
      t = new System.Windows.Forms.Timer();
      t.Interval = CalculateTimerInterval(CHECK_INTERVAL);
      t.Tick += new EventHandler(t_Tick);
      t.Start();
  }
  
  static void t_Tick(object sender, EventArgs e)
  {
      t.Interval = CalculateTimerInterval(CHECK_INTERVAL);
  }
  </code></pre>