1. 程式人生 > >27.8 執行定時計算限制操作(Timer)

27.8 執行定時計算限制操作(Timer)

 

        private static System.Threading.Timer s_Timer;
        static void Main()
        {
            Console.WriteLine("checking status every 2 seconds");
            s_Timer = new System.Threading.Timer(Status, null, Timeout.Infinite, Timeout.Infinite);
            s_Timer.Change(
2000, Timeout.Infinite); Console.ReadKey(); } private static void Status(object state) { Console.WriteLine("in status at {0}", DateTime.Now); Thread.Sleep(1000); //返回前讓timer 2s 後再觸發 s_Timer.Change(2000, Timeout.Infinite); }

 

        static void Main()
        {
            Console.WriteLine("checking status every 2 seconds");
            Status();
            Console.ReadKey();
        }
        private static async void Status()
        {
            while (true)
            {
                Console.WriteLine(
"in status at {0}", DateTime.Now); //要檢查的程式碼 //在迴圈末尾,在不阻塞執行緒的前提下延遲2s await Task.Delay(2000); //await 允許執行緒返回 //2s 之後,某個執行緒會在await之後介入並繼續迴圈 } }