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

后端 未结 9 614
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:35

    You can calculate how times your function will be call, and create decrement counter, after elapsed which you unsubscribe from timer tick. Or you can Run another timer which have tick period - 10 min and on tick you unsubscribe from timer tick calling your function.

    0 讨论(0)
  • 2021-01-02 07:36

    Have your timer loop something like this:

    DateTime endTime = DateTime.Now.AddMinutes(10);
    
    while(endTime < DateTime.Now)
    {
      // Process loop
    }
    
    0 讨论(0)
  • 2021-01-02 07:39

    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.

    0 讨论(0)
提交回复
热议问题