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 10:45

You could use a second timer:

class Program
{
    static void Main(string[] args)
    {
        int interval = 5 * 1000; //milliseconds
        int duration = 10 * 60 * 1000; //milliseconds

        intervalTimer = new System.Timers.Timer(interval);
        durationTimer = new System.Timers.Timer(duration);

        intervalTimer.Elapsed += new System.Timers.ElapsedEventHandler(intervalTimer_Elapsed);
        durationTimer.Elapsed += new System.Timers.ElapsedEventHandler(durationTimer_Elapsed);

        intervalTimer.Start();
        durationTimer.Start();
    }

    static void durationTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        intervalTimer.Stop();
        durationTimer.Stop();
    }

    static void intervalTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        //call your method
    }

    private static System.Timers.Timer intervalTimer;
    private static System.Timers.Timer durationTimer;
}
查看更多
成全新的幸福
3楼-- · 2019-02-13 10:46

Divide the Y minutes by the X interval to get how many times it needs to run. After that you just need to count how many times the function has been called.

In your case, 10 min = 600 seconds / 5 seconds = 120 calls needed. Just have a counter keep track of how many times your function has been called.

查看更多
▲ chillily
4楼-- · 2019-02-13 10:46

You can set two timers one that run for 5 secs and the other one that run for 10min and disable the first one

查看更多
Rolldiameter
5楼-- · 2019-02-13 10:49

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.

查看更多
Explosion°爆炸
6楼-- · 2019-02-13 10:55

Have your timer loop something like this:

DateTime endTime = DateTime.Now.AddMinutes(10);

while(endTime < DateTime.Now)
{
  // Process loop
}
查看更多
Evening l夕情丶
7楼-- · 2019-02-13 11:00

Timer.Stop() after 120 Ticks.

查看更多
登录 后发表回答