Execute an operation every x seconds for y minutes

2019-02-13 10:32发布

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?

标签: c# timer
9条回答
爷的心禁止访问
2楼-- · 2019-02-13 11:01

just use a DateTime variable to track when it should end and set that right before you start. The on your Elapsed event handler, check if the signal time is less than the end time. If it isn't, stop the timer.

查看更多
可以哭但决不认输i
3楼-- · 2019-02-13 11:05

Just capture the time that you want to stop and end your timer from within the elapsed handler. Here's an example (note: I used a System.Threading.Timer timer. Select the appropriate timer for what you are doing. For example, you might be after a System.Windows.Forms.Timer if you are writing in Winforms.)

public class MyClass
{
    System.Threading.Timer Timer;
    System.DateTime StopTime;
    public void Run()
    {
        StopTime = System.DateTime.Now.AddMinutes(10);
        Timer = new System.Threading.Timer(TimerCallback, null, 0, 5000);
    }

    private void TimerCallback(object state)
    {
        if(System.DateTime.Now >= StopTime)
        {
            Timer.Dispose();
            return;
        }
        // Do your work...
    }
}
查看更多
唯我独甜
4楼-- · 2019-02-13 11:07

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.

查看更多
登录 后发表回答