asp.net 定时执行程序

在一个项目中想实现以上功能,在项目中加入一个 Global.aspx文件即可实现。

public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            //定义定时器
            System.Timers.Timer myTimer = new System.Timers.Timer(5000);
            myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);
            myTimer.Enabled = true;
            myTimer.AutoReset = true;
        }

        void myTimer_Elapsed(object source, ElapsedEventArgs e)
        {
            try
            {
                Log.SaveNote(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":AutoTask is Working!");
                YourTask();
            }
            catch (Exception ee)
            {
                Log.SaveException(ee);
            }
        }

        void YourTask()
        {
            //在这里写你需要执行的任务
            Log.SaveNote(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":采集开始!");
        }


        protected void Application_End(object sender, EventArgs e)
        {
            Log.SaveNote(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":Application End!");

            //下面的代码是关键,可解决IIS应用程序池自动回收的问题
            Thread.Sleep(1000);
            //这里设置你的web地址,可以随便指向你的任意一个aspx页面甚至不存在的页面,目的是要激发Application_Start           
            string url = "http://localhost:8031/default.aspx";
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
            Stream receiveStream = myHttpWebResponse.GetResponseStream();//得到回写的字节流
           
        }
    }

 

demo下载

posted on 2010-02-06 12:35  xiaohu  阅读(2069)  评论(1编辑  收藏  举报