开发工具 Visual Studio 2010
using System; using System.Timers; namespace TestTimer { class Program { private static Timer aTimer; static void Main(string[] args) { aTimer = new Timer(); aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);//注册事件回调方法 aTimer.Interval = 1000;//每隔1秒触发一次Elapsed事件 aTimer.Enabled = true;//开启Timer Console.WriteLine("Press the Enter key to exit the program."); Console.ReadLine(); } static int i = 0; private static void OnTimedEvent(object source, ElapsedEventArgs e) { Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime); i++; if (i > 5) aTimer.Stop();//停止Timer } } }
运行效果