【ASP.NET 進階】定時執行任務


原理:利用全局應用程序類 Global.asax 和 System.Timers.Timer  類定時處理任務。

 

示例效果圖:

其 Global.asax 類代碼如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Timers;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

namespace TimingTask
{
    /**
     *原理:Global.asax 可以是asp.net中應用程序或會話事件處理程序,
     *我們用到了Application_Start(應用程序開始事件)和Application_End(應用程序結束事件)。
     *當應用程序開始時,啟動一個定時器,用來定時執行任務YourTask()方法,
     *這個方法里面可以寫上需要調用的邏輯代碼,可以是單線程和多線程。
     *當應用程序結束時,如IIS的應用程序池回收,讓asp.net去訪問當前的這個web地址。
     *這里需要訪問一個aspx頁面,這樣就可以重新激活應用程序。 
     */
    public class Global : System.Web.HttpApplication
    {
        //在應用程序啟動時運行的代碼  
        protected void Application_Start(object sender, EventArgs e)
        {
            //定時器
            System.Timers.Timer myTimer = new System.Timers.Timer(2000);
            myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);
            myTimer.Enabled = true;
            myTimer.AutoReset = true;
        }
        private void myTimer_Elapsed(object source, ElapsedEventArgs e)
        {
            try
            {
                RunTheTask();
            }
            catch (Exception ex)
            {
                WebForm1.html = ex.Message;
            }
        }

        private void RunTheTask()
        {
            //在這里寫你需要執行的任務
            WebForm1.html = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":AutoTask is Working!";
        }

        // 在新會話啟動時運行的代碼  
        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }
        // 在出現未處理的錯誤時運行的代碼  
        protected void Application_Error(object sender, EventArgs e)
        {

        }
        // 在會話結束時運行的代碼。   
        protected void Session_End(object sender, EventArgs e)
        {
            // 注意: 只有在 Web.config 文件中的 sessionstate 模式設置為  
            // InProc 時,才會引發 Session_End 事件。如果會話模式設置為 StateServer   
            // 或 SQLServer,則不會引發該事件
        }
        //  在應用程序關閉時運行的代碼  
        protected void Application_End(object sender, EventArgs e)
        {
            WebForm1.html = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":Application End!";

            //下面的代碼是關鍵,可解決IIS應用程序池自動回收的問題  

            Thread.Sleep(1000);

            //這里設置你的web地址,可以隨便指向你的任意一個aspx頁面甚至不存在的頁面,目的是要激發Application_Start  
            string url = "WebForm1.aspx";
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
            Stream receiveStream = myHttpWebResponse.GetResponseStream();//得到回寫的字節流  
        }
    }
}

 

然后用 WebForm 頁面輸出定時效果:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TimingTask
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        public static String html = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetDataBind();
            }
        }

        private void GetDataBind()
        {
            for (int i = 0; i <10; i++)
            {
                System.Threading.Thread.Sleep(1000);
                Response.Write(html+"<br />");
            }
        }
    }
}

 


免責聲明!

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



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