Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute timer when right after started?

Tags:

c#

timer

I have a timer with interval 3600000 which can be translated into an hour, so when I do

timer.Start()

it will it will execute code below in every hour starting from next hour

private void timer_Tick(object sender, EventArgs e)
{
    .....
}

but what if I want it to be also executed the second I call timer.Start() and then every hour after?

like image 209
Hendra Anggrian Avatar asked Jun 24 '13 19:06

Hendra Anggrian


2 Answers

The simplest option would be to just call the method:

timer.Start();
timer_Tick(null, EventArgs.Empty); // Simulate a timer tick event

This doesn't actually trigger the timer, but calls your handler immediately, effectively simulating a "now" event.

like image 148
Reed Copsey Avatar answered Nov 19 '22 16:11

Reed Copsey


As I understand System.Threading.Timer does exactly what you want.

It allows you to specify when the first invocation must occur and then the interval between invocations.

So if you set the first invocation to 0 milliseconds and the interval to an hour, it will fire immediately and then every hour.

dueTime Type: System.Int32 The amount of time to delay before callback is invoked, in milliseconds. Specify Timeout.Infinite to prevent the timer from starting. Specify zero (0) to start the timer immediately.

period Type: System.Int32 The time interval between invocations of callback, in milliseconds. Specify Timeout.Infinite to disable periodic signaling.

like image 20
Quinton Bernhardt Avatar answered Nov 19 '22 15:11

Quinton Bernhardt