How to fire timer.Elapsed event immediately

Viewed 85455

I'm using the System.Timers.Timer class to create a timer with an Timer.Elapsed event. The thing is the Timer.Elapsed event is fired for the first time only after the interval time has passed.

Is there a way to raise the Timer.Elapsed event right after starting the timer ?

I couldn't find any relevant property in the System.Timers.Timer class.

10 Answers

For the first time, the timer will start after 1 second. After that, its interval will be changed to every 30 seconds or whatever...

    //main function    
    Timer timer = new Timer(1000);   //initial start after 1 second
        timer.Elapsed += new ElapsedEventHandler(TimerElapsedMethod);
        timer.Start();            
    }
    private void TimerElapsedMethod(object sender, ElapsedEventArgs e) 
    {
        Timer timer = (Timer)sender; // Get the timer that fired the event
        timer.Interval = 30000;      // Change the interval to whatever
        .
        .
        .
    }

I'm not a pro so take this with a pinch of salt but it works. I created a function and instead of putting my code into the timer sub I put it into the function. Then I merely called the function when I wanted it (in my case on page load) and then the timer code would fire at the interval times and simply call the function in the timer sub code.

Here is the easy answer. (Assuming you're using a Windows form)

After dragging your timer control to your form, set the enabled property to true, and the Interval property to whatever you want the initial value to be. (100 is the default and will start the tick event immediately)

enter image description here

Then within your tick event, simply check the value of the Interval property. If it is not your desired value, set it. It's that simple. The same can be accomplished in your C# code if creating a timer on the fly.

enter image description here

Related