Asp.net定時執行程式

來源:互聯網
上載者:User

 用Timer解決問題的思路很簡單,首先設定Timer類的Interval屬性(單位是毫秒),也就是時間間隔;然後在Timer的Elapsed的事件裡寫執行代碼,每過一個設定好的Interval時間間隔,將執行一次Elapsed中的事件 (這和VB程式中的Timer控制項基本沒有區別)。
那知道了用什麼類,這些代碼要寫在哪裡呢?把代碼寫在Global.asax件中,在VS的項目上右鍵,點添加--》建立項,選“全域應用程式類”,項目中就會有Global.asax檔案了。

為了表達清楚直接上代碼(首先在Global.asax檔案頭部引入system.Timers命名控制項):

<span style="font-size:18px;">    public class Global : System.Web.HttpApplication    {        //在網站運行時這段代碼同時啟動        protected void Application_Start(object sender, EventArgs e)        {                        System.Timers.Timer objTimer = new System.Timers.Timer();            objTimer.Interval = 60*1000;    //這個時間單位:毫秒            objTimer.Enabled = true;        //設定Timer類的可用性            //將Timer的Elapsed事件綁定到建立立的timer對象上            objTimer.Elapsed += new ElapsedEventHandler(objTimer_Elapsed);         }</span>

下面是在Timer的Elapsed事件中的代碼

<span style="font-size:18px;">void objTimer_Elapsed(object sender, ElapsedEventArgs e){                        string Time = DateTime.Now.ToShortTimeString();//獲得目前時間//從設定檔裡獲得當前設定的時間。            string OrderTime = ConfigurationManager.AppSettings["OrderFoodTime"];            /*測試資料*/            if(Time.Equals(OrderTime))            {                //如果時間相等,執行你要執行的操作,這裡可以調用你程式中的其他類的方法            }}</span>

這樣就能達到定時執行程式的目的了。

這是用在我項目中的定時執行,在論壇裡問關於定時執行的方案,也有人說用windows服務比較安全

聯繫我們

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