1. 程式人生 > >定時器&改變定時器的執行頻率

定時器&改變定時器的執行頻率

rgs class lin 調用 key sys art console datetime

技術分享圖片

 static System.Threading.Timer timer; 
        static void Main(string[] args)
        {
            Console.WriteLine("Press Enter key to stop timer");
            DateTime start = DateTime.Now;
            //啟動定時器,每2秒執行一次
            timer = new Timer(p => TimerOperation(start),null,TimeSpan.FromSeconds(1
),TimeSpan.FromSeconds(2)); //休眠10秒,10/2=5,即定時器執行5次 Thread.Sleep(TimeSpan.FromSeconds(10)); //在修改為調用change方法1秒後啟動TimerOperation,然後每5秒執行一次 timer.Change(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); Console.ReadLine(); timer.Dispose(); }
static void TimerOperation(DateTime start) { TimeSpan elapsed = DateTime.Now - start; Console.WriteLine("{0} seconds from {1}. timer thead pool thread id : {2}",elapsed.Seconds,start,Thread.CurrentThread.ManagedThreadId); }

技術分享圖片

定時器&改變定時器的執行頻率