Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a .net System.Timers.Timer fire immediately

Tags:

I am using a Timer to run an event periodically on a reasonably long interval (2 minutes). This is working fine. However I would like the event to fire immediately when the timer is created (instead of waiting 2 minutes).

Note that I can't do this just by calling the method, since it takes some time to run and would block the application. I need the timer to fire as normal and run the event in a separate thread.

The best way I can think of doing this at the moment is subclassing the timer and creating a TriggerManually method that would do something like this:

  • Turn auto reset off
  • Set the interval to 1ms
  • Enable the timer

This would trigger the elapsed event straight away, and I could put all the settings back to normal.

Seems a bit roundabout though. Is there a better way to do it?

like image 825
Nathan Avatar asked Aug 02 '10 03:08

Nathan


People also ask

How do you fire timer elapsed event immediately?

Just call the Timer_Tick method yourself. As pointed out by @Yahia, you could also use the System. Threading. Timer timer, which you can set to have an initial delay to 0.

How do I stop a timer elapsed event?

It would have already queued before you have called Stop method. It will fire at the elapsed time. To avoid this happening set Timer. AutoReset to false and start the timer back in the elapsed handler if you need one.

Which event is generally used with timer in C#?

Elapsed event every two seconds (2,000 milliseconds), sets up an event handler for the event, and starts the timer.


1 Answers

Couldn't you just call your event handler for the elapsed event manually?

Even if you were expecting it to execute on a thread pool thread, you could invoke it.

class Blah {     private Timer mTimer;      public Blah()     {         mTimer = new Timer(120000);          ElapsedEventHandler handler = new ElapsedEventHandler(Timer_Elapsed);         mTimer.Elapsed += handler;         mTimer.Enabled = true;          //Manually execute the event handler on a threadpool thread.         handler.BeginInvoke(this, null, new AsyncCallback(Timer_ElapsedCallback), handler);     }      private static void Timer_Elapsed(object source, ElapsedEventArgs e)     {         //Do stuff...     }      private void Timer_ElapsedCallback(IAsyncResult result)     {         ElapsedEventHandler handler = result.AsyncState as ElapsedEventHandler;         if (handler != null)         {             handler.EndInvoke(result);         }     } } 
like image 74
Rob Cooke Avatar answered Sep 18 '22 19:09

Rob Cooke