9

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?

4

3 回答 3

12

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.

于 2013-06-24T19:47:44.923 回答
2

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.

于 2013-06-24T19:52:35.267 回答
0

Simply I would do right after you call Start(), call the function manually.

于 2013-06-24T19:47:58.850 回答