在c#中每x秒执行一次操作,持续y分钟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/786672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 01:06:51  来源:igfitidea点击:

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

c#timer

提问by

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

我需要每 5 秒运行一次函数,持续 10 分钟。

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

我使用计时器运行 5 秒,但如何将计时器限制为仅 10 分钟?

回答by JP Alioto

Timer.Stop()after 120 Ticks.

Timer.Stop()在 120 个滴答之后。

回答by Adam Wright

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

注意开始时间。在每次调用中,测试是否 currentTime + 5 秒 > startTime + 10 分钟。如果是这样,请禁用计时器。

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.

我更喜欢这种方,而不是只运行 N 个滴答声,因为不能保证定时器在你想要的时候触发。在 10 分钟的现实世界时间中,可能有 120 个滴答声。

回答by Darren Kopp

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.

只需使用 DateTime 变量来跟踪它应该何时结束并在开始之前设置它。在 Elapsed 处理程序上,检查信号时间是否小于结束时间。如果不是,请停止计时器。

回答by Maksim Kondratyuk

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.

您可以计算您的函数将被调用的次数,并在您取消订阅计时器滴答后创建递减计数器。或者,您可以运行另一个具有滴答周期的计时器 - 10 分钟,然后在滴答时取消订阅调用您的函数的计时器滴答。

回答by user39113

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.

将 Y 分钟除以 X 间隔以获得它需要运行的次数。之后,您只需要计算函数被调用的次数。

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.

在您的情况下,10 分钟 = 600 秒/5 秒 = 需要 120 次调用。只需有一个计数器记录您的函数被调用的次数。

回答by Peter Mourfield

Have your timer loop something like this:

让你的计时器循环是这样的:

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

while(endTime < DateTime.Now)
{
  // Process loop
}

回答by Hannoun Yassir

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

您可以设置两个计时器,一个运行 5 秒,另一个运行 10 分钟并禁用第一个

回答by JMarsch

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.Timertimer. Select the appropriate timer for what you are doing. For example, you might be after a System.Windows.Forms.Timerif you are writing in Winforms.)

只需在经过处理的处理程序中捕获您想要停止和结束计时器的时间。这是一个示例(注意:我使用了System.Threading.Timertimer. 为您正在做的事情选择合适的计时器。例如,System.Windows.Forms.Timer如果您在 Winforms 中编写,您可能会在 a 之后。)

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

回答by scottm

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