【ASP.NET 進階】定時執行任務實現 (定時讀取和修改txt文件數字內容,無刷新顯示結果)


現在有很多網站或系統需要在服務端定時做某件事情,如每天早上8點半清理數據庫中的無效數據等等,Demo 具體實現步驟如下:

0.先看解決方案截圖

1.創建ASP.NET項目TimedTask,然后新建一個全局應用程序類文件 Global.asax

2.然后在Application_Start 事件中 啟動定時器,如需要每隔多少秒來做一件事情,即在后台執行,與客戶端無關,即使客戶端全部都關閉,那么后台仍然執行,具體代碼如下:

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 TimedTask
{
    public class Global : System.Web.HttpApplication
    {
        private void AddCount(object sender, ElapsedEventArgs e)
        {
            //在這里編寫需要定時執行的邏輯代碼
            FileControl.ChangeFileNumber();
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            System.Timers.Timer timer = new System.Timers.Timer();
            //AddCount是一個方法,此方法就是每個1秒而做的事情
            timer.Elapsed += new System.Timers.ElapsedEventHandler(AddCount);
            timer.Interval = 1000;// 設置引發時間的時間間隔,此處設置為1秒
            timer.Enabled = true;
            timer.AutoReset = true;
        }

        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)
        {
            //  在應用程序關閉時運行的代碼  
            //下面的代碼是關鍵,可解決IIS應用程序池自動回收的問題  
            //局限性:可以解決應用程序池自動或者手動回收,但是無法解決IIS重啟或者web服務器重啟的問題,當然這種情況出現的時候不多,而且如果有人訪問你的網站的時候,又會自動激活計划任務了。  
            Thread.Sleep(1000);
            //這里設置你的web地址,可以隨便指向你的任意一個aspx頁面甚至不存在的頁面,目的是要激發Application_Start  
            string url = "http://www.cnblogs.com/yc-755909659/";
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
            Stream receiveStream = myHttpWebResponse.GetResponseStream();//得到回寫的字節流  
        }

        /*原理:Global.asax 可以是asp.net中應用程序或會話事件處理程序,我們用到了Application_Start(應用程序開始事件)和Application_End(應用程序結束事件)。
         * 當應用程序開始時,啟動一個定時器,用來定時執行任務AddCount()方法,這個方法里面可以寫上需要調用的邏輯代碼,可以是單線程和多線程。
         * 當應用程序結束時,如IIS的應用程序池回收,讓asp.net去訪問當前的這個web地址。這里需要訪問一個aspx頁面,這樣就可以重新激活應用程序。*/
    }
}
Global.asax

3.簡單的循環事件實現:讀取txt文件中的數字,實現每秒遞加

(1) 先新建 testfile.txt 文件,里面為數字1。

(2) 讀取和修改txt文件實現:

    public class FileControl
    {
        private const string testFilePath = "~/testfile.txt";
        public static string GetFileNumber()
        {
            //獲得物理路徑
            string filePath = System.Web.Hosting.HostingEnvironment.MapPath(testFilePath); string text = System.IO.File.ReadAllText(filePath);
            return text;
        }

        public static string ChangeFileNumber()
        {
            string text = GetFileNumber();
            string newText = (int.Parse(text) + 1) + ""; //數字增加1
            string filePath = System.Web.Hosting.HostingEnvironment.MapPath(testFilePath);
            System.IO.File.WriteAllText(filePath, newText, System.Text.Encoding.UTF8);
            return text;
        }
    }

4.測試頁面利用官方控件無刷新實現文件數字顯示

(1) Html代碼

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Test</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <input id="txtValue" type="text" />
            <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <asp:Timer ID="Timer1" runat="server" Interval="1000" OnTick="Timer1_Tick"></asp:Timer>
                    <asp:Label ID="lb_Value" runat="server" Text="1"></asp:Label>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>

(2)cs 代碼

namespace TimedTask
{
    public partial class TestForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                TimeStart();
            }
        }
        protected void Timer1_Tick(object sender, EventArgs e)
        {
            TimeStart();
        }
        private void TimeStart()
        {
            lb_Value.Text = "Runtime:" + FileControl.GetFileNumber() + " s";
        }
    }
}

實現效果:

 

源代碼:TimedTask.zip


免責聲明!

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



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