asp.net簡單定時任務實現

來源:互聯網
上載者:User

標籤:instance   set   images   oba   line   編寫   deb   ret   代碼   

代碼如下:

    public class TimeTask    {        #region 單例        private static TimeTask _task = null;        public static TimeTask Instance        {            get            {                if (_task == null)                {                    _task = new TimeTask();                }                return _task;            }        }        #endregion        //事件        public event System.Timers.ElapsedEventHandler ExecuteTask;        //時間對象        private System.Timers.Timer _timer = null;        //定義時間間隔        private int _interval = 1000;//預設1秒鐘        public int Interval        {            set            {                _interval = value;            }            get            {                return _interval;            }        }        //開始        public void Start()        {            if (_timer == null)            {                _timer = new System.Timers.Timer(_interval);                _timer.Elapsed += new System.Timers.ElapsedEventHandler(_timerElapsed);                _timer.Enabled = true;                _timer.Start();            }        }        //委託方法,映射到傳入的值        protected void _timerElapsed(object sender, System.Timers.ElapsedEventArgs e)        {            if (null != ExecuteTask)            {                ExecuteTask(sender, e);            }        }        //停止        public void Stop()        {            if (_timer != null)            {                _timer.Stop();                _timer.Dispose();                _timer = null;            }        }    }

調用方式,在Global.asax中,代碼如下:

     protected void Application_Start(object sender, EventArgs e)        {            // 在應用程式啟動時啟動並執行代碼              TimeTask.Instance.ExecuteTask += new System.Timers.ElapsedEventHandler(TimeExecuteTask);            TimeTask.Instance.Interval = 1000 * 10;//時間間隔,10秒鐘            TimeTask.Instance.Start();        }        void TimeExecuteTask(object sender, System.Timers.ElapsedEventArgs e)        {            //在這裡編寫需要定時執行的邏輯代碼            System.Diagnostics.Debug.WriteLine("定時任務執行" + DateTime.Now);        }

說明:由於IIS會進行回收,所以還需要在IIS的線程池上配置不讓其回收。如下:

回收:

固定時間間隔(分鐘) 改為 0

虛擬/專用記憶體限制(KB) 改為 0

進程模型:

閑置逾時(分鐘) 改為 0

 

asp.net簡單定時任務實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.