2014-12-27 287 views
-1

我正在尝试制作一个程序,它每x分钟执行一次。我一直在尝试使用秒表功能,但它似乎并没有运行我想要的代码,当时间到了。每x分钟运行一次代码

这里是我的代码:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Diagnostics; 
using System.Threading; 

namespace Testing 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Stopwatch testing = new Stopwatch(); 
      testing.Start(); 

      Thread.Sleep(6001); 
      TimeSpan ts = testing.Elapsed; 
      int timer = Convert.ToInt32(String.Format("{0}", ts.Seconds)); 
      Console.Write(timer); 

      while (testing.Elapsed < TimeSpan.FromMinutes(8)) 
      { 

       timer = Convert.ToInt32(String.Format("{0}", ts.Seconds)); 
       if (timer % 60 == 0) 
       { 
        //run x code every 1 minutes 
        Console.WriteLine("1 min" + timer); 
       } 


       timer = Convert.ToInt32(String.Format("{0}", ts.Seconds)); 
       if (timer % 120 == 0) 
       { 
        //run x code every 2 minutes 
        Console.WriteLine("2 min" + timer); 
       } 
      }  

      testing.Stop(); 
     } 
    } 
} 

回答

1

至于建议的xxbbcc,这里是一个使用ManualResetEvent.WaitOne()的实现与超时:您的回复

static void Main(string[] args) 
    { 
     int TimeOut = (int)TimeSpan.FromMinutes(2).TotalMilliseconds; 
     System.Threading.ManualResetEvent mreDuration = new System.Threading.ManualResetEvent(false); 
     Task.Run(() => { 
      System.Threading.Thread.Sleep((int)TimeSpan.FromMinutes(30).TotalMilliseconds); 
      mreDuration.Set(); 
     }); 
     while(!mreDuration.WaitOne(TimeOut)) 
     { 
      Console.WriteLine("Two Minutes..."); 
     } 
     Console.WriteLine("Thirty Mintues!"); 
     Console.ReadLine(); 
    } 
2

Stopwatch是一款高性能定时器(通常具有100ns的分辨率) - 它是你想要做什么完全不恰当的。 Stopwatch用于通过拍摄系统计数器的快照然后计算差值来测量时间。由于调度程序的大部分工作都是等待工作完成,因此使用紧密循环实现调度程序效率极低 - 系统正在使用CPU资源来决定在大多数情况下不执行任何操作。

要正确实施调度程序(如果这是您要做的),请使用带有超时选项的ManualResetEvent进行调查。

使用事件会使当前线程进入睡眠状态(因此不会在系统资源不做任何操作时使用系统资源),并且当超时到期时,触发事件并且代码可以调用您正在尝试调度的函数。

如果您只想告诉您什么时间间隔已过,您可以使用System.Timers.Timer代替:这样可以更简单地安排回调(在计时器到期时调用Elapsed事件),而您不需要在等待期间必须运行一个循环。

编辑:

如果你只是想以定期调用回调函数,一个简单的定时器更容易挂钩不是一个事件。下面是使用System.Timer代码示例(不是我的代码,我复制&从MSDN粘贴本,上面链接):

private static Timer m_oTimer; 

public static void Main() 
{ 
    m_oTimer = new System.Timers.Timer (2 * 1000 * 60); // 2 minutes 
    m_oTimer.Elapsed += OnTimedEvent; // Timer callback 
    m_oTimer.Enabled = true; // Start timer 

    // Wait here (you can do other processing here, too) 
    Console.WriteLine ("Press the Enter key to exit the program... "); 
    Console.ReadLine(); 
    Console.WriteLine ("Terminating the application..."); 
} 

private static void OnTimedEvent (Object source, ElapsedEventArgs e) 
{ 
    // This is called on a separate thread; do periodic processing here 
    Console.WriteLine ("The Elapsed event was raised at {0}", e.SignalTime); 
} 
+0

嗨xxbbcc,谢谢。根据你的建议,我一直在尝试使用ManualResetEvent,因为它似乎适合我想要做的更多,但是我只能设法使代码运行一次使用计时器,我所寻找的是每x分钟,该代码将运行一次。 例如,我将程序运行时间设置为30分钟。在30分钟的运行时间内,我希望程序每隔2分钟重复Console.WriteLine(“2分钟已到”),直到30分钟结束。请帮我:) – Konny

+0

@Konny我用'System.Timers.Timer'用一些代码更新了我的答案。 – xxbbcc

0

您应该使用Timer。如果你希望计时器在停止运行后,比如'y'分钟,那么你只需将开始时间存储在一个变量中,并写入Timer.Stop()函数,以便在'y'分钟后执行(提示:将其写入timer_tick事件中)。定时器的时间段应为HCF全部为x's和y。请记住以毫秒为单位设置时间段。