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

后端 未结 9 612
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:33

    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...
        }
    }
    

提交回复
热议问题