tags:

views:

73

answers:

3

How do I get a timer event to fire one at a time. For example I have a timer that raises an event every 10 minutes. The event that is raised takes 10 or more minutes to finish executing. I would like the timer to reset AFTER the event has finished. In other words I do not want to raise more than 1 instance of the event at any one time.

+5  A: 

Usually what I do is have my event stop the timer when it's raised and then restart the timer when the event process completes:

private void timerHandler(object sender, TimerElapsedEventArgs e)
{
    Timer timer = (Timer)sender;
    timer.Stop();
    RunProcess();
    timer.Start();
}

public void RunProcess()
{
    /* Do stuff that takes longer than my timer interval */
}

Now my timer will start again on completion of the process

BenAlabaster
+3  A: 

Use System.Timers.Timer not the Threading one

Set AutoReset to false.

Then Start it again when you're done.

Conrad Frix
+1 for `MyTimer.AutoReset = false`. Otherwise someone might forget to manually manage the `Start()` and `Stop()` calls.
Onion-Knight
A: 

It may be difficult to stop timers for efficiency or logic. The following code synchronizes skipping the events.

static readonly object key = new object();

void TimerHandler(object sender, TimerElapsedEventArgs e)
{
  if(Monitor.TryEnter(key))
  {
    try
    {
      //do your stuff
    }
    finally
    {
      Montitor.Exit(key);
    }
  }
}
Rohit