首页 > Web开发 > 详细

asp.net简单定时任务实现

时间:2017-01-20 14:40:02      阅读:228      评论:0      收藏:0      [点我收藏+]

代码如下:

    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简单定时任务实现

原文:http://www.cnblogs.com/EasonJim/p/6322580.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!