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

后端 未结 9 688
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:31

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

提交回复
热议问题