My timer 'Elapsed' event fires twice when the program is started. The only assignment of the 'Elapsed' event handler is in 'Main' method. Is there something that I'm doing wrong?
//class level clock
public static System.Timers.Timer Clock;
static void Main(string[] args)
{
Clock = new System.Timers.Timer();
Clock.Elapsed += new ElapsedEventHandler(Clock_Elapsed);
Clock.AutoReset = false;
Clock.Interval = timerInterval; //this needs to be in milliseconds!
Clock.Enabled = true;
//run infinite loop until q is pressed
while (Console.Read() != 'q')
{}
}
static void Clock_Elapsed(object sender, ElapsedEventArgs e)
{
Clock.Stop();
//do some stuff
Clock.Start();
}
UPDATE:
The AutoReset provided by @fparadis2 fixed the firing twice. The base issue was that my timer interval was set to 30 milliseconds instead of 30000 milliseconds(30 seconds) so that the event was double firing.
timer. Start(); when you call the Start method timer starts ticking next moment and it starts firing the Elapsed event based on the interval set, and it keep ticking/firing Elapsed event for the interval you set at Step3 untill you execute the timer. Stop method.
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.
Elapsed event every two seconds (2000 milliseconds), sets up an event handler for the event, and starts the timer. The event handler displays the value of the ElapsedEventArgs. SignalTime property each time it is raised.
If timerInverval is small enough, it might be possible that the Elapsed event is fired twice before you get the chance to stop the clock. You should do
Clock.AutoReset = false;
in order to be notified only once each time you start the timer.
As specified in the Timer Class documentation:
If processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. In this situation, the event handler should be reentrant.
You may also consider checking this pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With