I have a Console App and in the main method, I have code like this:
Timer time = new Timer(seconds * 1000); //to milliseconds
time.Enabled = true;
time.Elapsed += new ElapsedEventHandler(time_Elapsed);
I only want the timer to run once so my idea is that I should stop the timer in the time_Elapsed method. However, since my timer exists in Main(), I can't access it.
I assume that you're using
System.Timers.Timer
rather thanSystem.Windows.Forms.Timer
?You have two options.
First, as probably the best, is to set the
AutoReset
property tofalse
. This should do exactly what you want.The other option is to call
Stop
in the event handler.You have access to the Timer inside of the
timer_Elapsed
method:The above method will stop whatever Timer fired the Event (in case you have multiple Timers using the same handler and you want each Timer to have the same behavior).
You could also set the behavior when you instantiate the Timer:
A little example app:
You may also use the System.Threading.Timer. Its constructor takes two time-related parameters:
Set the period to Timeout.Infinite to prevent from firing again.