Execute an operation every x seconds for y minutes in c#

后端 未结 9 658
Happy的楠姐
Happy的楠姐 2021-01-02 06:45

I need to run a function every 5 seconds for 10 minutes.

I use a timer to run it for 5 secs, but how do I limit the timer to only 10 mins?

9条回答
  •  北海茫月
    2021-01-02 07:34

    Note the start time. In each call, test if currentTime + 5 seconds > startTime + 10 minutes. If so, disable the timer.

    I prefer this approach to just running for N ticks, as timers are not guaranteed to fire when you'd like them to. It's possible 120 ticks may run over 10 minutes of real world time.

提交回复
热议问题