asp.net簡單定時任務實現


代碼如下:

    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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM