sportdog

导航

 

 

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

        }

posted on 2018-08-27 15:09  sportdog  阅读(609)  评论(0编辑  收藏  举报