none
System.Timers.Timer question. RRS feed

  • Question

  • I am using the timers to process periodic tasks, but want it to run when it first starts and then wait for the interval and I'm having trouble figuring that out.
    This will normally be a fairly long interval and I'd prefer not to wait till it expires to get a process when it first initiates. Is there a good way to to tell it to fire off an event when it first starts?
    The controlling application, based on config data, spawns one or more timers that will do some processing each time they wake up.  I like allowing the thread-pool to handle that chore and don't want to fire up threads of my own to get an initial run and *then* sleeping for the interval.  If I have to write all that threading code myself I might as well not use the timers.
    Friday, May 22, 2009 6:36 PM

Answers

  • You could use the System.Threading.Timer which has a constructor that does what you want, if you don't particularly need the System.Timers.Timer instead.
    • Marked as answer by Zhi-Xin Ye Thursday, May 28, 2009 10:31 AM
    Friday, May 22, 2009 6:50 PM
  • Yup.  And it is a much better timer since it doesn't swallow exceptions.  An entirely different approach is a worker thread.  Use ManualResetEvent.WaitOne(int) in a loop to make it periodic. The MRE gives you a good way to stop the thread.  The advantage of a thread is that you won't crash and burn on OOM when the amount of time spend in the timer callback is larger than the timer period.

    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Thursday, May 28, 2009 10:32 AM
    Friday, May 22, 2009 7:05 PM
    Moderator

All replies

  • You could use the System.Threading.Timer which has a constructor that does what you want, if you don't particularly need the System.Timers.Timer instead.
    • Marked as answer by Zhi-Xin Ye Thursday, May 28, 2009 10:31 AM
    Friday, May 22, 2009 6:50 PM
  • Yup.  And it is a much better timer since it doesn't swallow exceptions.  An entirely different approach is a worker thread.  Use ManualResetEvent.WaitOne(int) in a loop to make it periodic. The MRE gives you a good way to stop the thread.  The advantage of a thread is that you won't crash and burn on OOM when the amount of time spend in the timer callback is larger than the timer period.

    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Thursday, May 28, 2009 10:32 AM
    Friday, May 22, 2009 7:05 PM
    Moderator