C# Timer應用

來源:互聯網
上載者:User

     單純的Timer應用其實不算複雜,幾個參數根據自己的情況設定就好了。如下面這段代碼:

     private void Run()      {          TimerCallback tcb = new TimerCallback(executeRun);         //Timer在5秒中後(DueTime)開始執行,之後每隔1秒(Period)執行一次          Timer timer = new Timer(tcb, null, 5000, 1000);      }      private void executeRun(object obj)      {          Console.WriteLine("Timer  Is Running at" + DateTime.Now.ToString());      }
    在我們ScheduledJob專案中有些Job採取的就是這種方式:每隔一段特定的時間執行一次;
但是有些時候,job的執行並沒有這麼規律,它可能是每個月一號執行一次,或許在周一執行一次,也或許是在每天的早上三點,下午三點分別執行一次,
此時就不得不對Timer採取另外一種用法:當次Job執行完畢後,根據設定檔計算出下次要執行的時間點,以此計算當前與下次執行的時間點作為DueTime,
並對Timer的DueTime進行變更。下面這段代碼示範如何利用Change方法變更DueTime。
using System;using System.Collections.Generic;using System.Threading;namespace fileSystemWatcherDemo{    /// <summary>    /// 示範Timer DueTime變更    /// </summary>    class TimerDemo    {        Dictionary<string, Timer> timerPool;        private int dutTime = 1;        static void Main(string[] args)        {            TimerDemo demo = new TimerDemo();            demo.beginRun();
            Console.Read();        }        private void beginRun()        {            timerPool = new Dictionary<string, Timer>();            for (int i = 1; i <= 1; i++)            {                TimerCallback tcb = new TimerCallback(execute);                //Timeout.Infinite指定Timer在DueTime後開始執行並只執行一次,若要再次執行,需使用Change方法重新指定DueTime                Timer timer = new Timer(tcb, i.ToString(), getDueTime(dutTime), Timeout.Infinite);                timerPool.Add(i.ToString(), timer);            }        }        private void execute(object obj)        {            string ep = obj as string;            if (ep != null)            {                Console.WriteLine("Timer " + ep + " Is Running at" + DateTime.Now.ToString());                Timer timer = timerPool[ep];                timer.Change(getDueTime(dutTime++), Timeout.Infinite);//使用Change方法重新指定DueTime            }        }        private long getDueTime(int i)        {            return Convert.ToInt64(i * 1000);        }    }}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.