国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

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

2019-11-14 14:31:13
字體:
來源:轉載
供稿:網友

現在有很多網站或系統需要在服務端定時做某件事情,如每天早上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.survivalescaperooms.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


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 江都市| 布拖县| 合肥市| 洛宁县| 富锦市| 台北县| 繁昌县| 济宁市| 黑水县| 全南县| 东至县| 彭泽县| 新沂市| 井陉县| 临漳县| 滕州市| 应城市| 襄汾县| 共和县| 南靖县| 房产| 恩平市| 五原县| 蓝山县| 永泰县| 钟祥市| 嘉义县| 安达市| 泗阳县| 大足县| 斗六市| 麦盖提县| 内江市| 邛崃市| 浮山县| 玉溪市| 遵义市| 青冈县| 余干县| 拉孜县| 伊川县|