asp.net 定時執行程式

來源:互聯網
上載者:User

在一個項目中想實現以上功能,在項目中加入一個 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();//得到回寫的位元組流
           

        }
    }

原文:

http://www.cnblogs.com/yangxiaohu1/archive/2010/02/06/net-autotask.html

聯繫我們

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