現(xiàn)在有很多網(wǎng)站或系統(tǒng)需要在服務(wù)端定時(shí)做某件事情,如每天早上8點(diǎn)半清理數(shù)據(jù)庫中的無效數(shù)據(jù)等等,Demo 具體實(shí)現(xiàn)步驟如下:
0.先看解決方案截圖
1.創(chuàng)建asp.net項(xiàng)目TimedTask,然后新建一個(gè)全局應(yīng)用程序類文件 Global.asax
2.然后在application_Start 事件中 啟動(dòng)定時(shí)器,如需要每隔多少秒來做一件事情,即在后臺(tái)執(zhí)行,與客戶端無關(guān),即使客戶端全部都關(guān)閉,那么后臺(tái)仍然執(zhí)行,具體代碼如下:
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) { //在這里編寫需要定時(shí)執(zhí)行的邏輯代碼 FileControl.ChangeFileNumber(); } protected void Application_Start(object sender, EventArgs e) { System.Timers.Timer timer = new System.Timers.Timer(); //AddCount是一個(gè)方法,此方法就是每個(gè)1秒而做的事情 timer.Elapsed += new System.Timers.ElapsedEventHandler(AddCount); timer.Interval = 1000;// 設(shè)置引發(fā)時(shí)間的時(shí)間間隔,此處設(shè)置為1秒 timer.Enabled = true; timer.AutoReset = true; } protected void Session_Start(object sender, EventArgs e) { // 在新會(huì)話啟動(dòng)時(shí)運(yùn)行的代碼 } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { // 在出現(xiàn)未處理的錯(cuò)誤時(shí)運(yùn)行的代碼 } protected void Session_End(object sender, EventArgs e) { // 在會(huì)話結(jié)束時(shí)運(yùn)行的代碼 // 注意: 只有在 Web.config 文件中的 sessionstate 模式設(shè)置為 InProc 時(shí),才會(huì)引發(fā) Session_End 事件。如果會(huì)話模式設(shè)置為 StateServer 或 SQLServer,則不會(huì)引發(fā)該事件 } protected void Application_End(object sender, EventArgs e) { // 在應(yīng)用程序關(guān)閉時(shí)運(yùn)行的代碼 //下面的代碼是關(guān)鍵,可解決IIS應(yīng)用程序池自動(dòng)回收的問題 //局限性:可以解決應(yīng)用程序池自動(dòng)或者手動(dòng)回收,但是無法解決IIS重啟或者web服務(wù)器重啟的問題,當(dāng)然這種情況出現(xiàn)的時(shí)候不多,而且如果有人訪問你的網(wǎng)站的時(shí)候,又會(huì)自動(dòng)激活計(jì)劃任務(wù)了。 Thread.Sleep(1000); //這里設(shè)置你的web地址,可以隨便指向你的任意一個(gè)aspx頁面甚至不存在的頁面,目的是要激發(fā)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();//得到回寫的字節(jié)流 } /*原理:Global.asax 可以是asp.net中應(yīng)用程序或會(huì)話事件處理程序,我們用到了Application_Start(應(yīng)用程序開始事件)和Application_End(應(yīng)用程序結(jié)束事件)。 * 當(dāng)應(yīng)用程序開始時(shí),啟動(dòng)一個(gè)定時(shí)器,用來定時(shí)執(zhí)行任務(wù)AddCount()方法,這個(gè)方法里面可以寫上需要調(diào)用的邏輯代碼,可以是單線程和多線程。 * 當(dāng)應(yīng)用程序結(jié)束時(shí),如IIS的應(yīng)用程序池回收,讓asp.net去訪問當(dāng)前的這個(gè)web地址。這里需要訪問一個(gè)aspx頁面,這樣就可以重新激活應(yīng)用程序。*/ }}
3.簡(jiǎn)單的循環(huán)事件實(shí)現(xiàn):讀取txt文件中的數(shù)字,實(shí)現(xiàn)每秒遞加
(1) 先新建 testfile.txt 文件,里面為數(shù)字1。
(2) 讀取和修改txt文件實(shí)現(xiàn):
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) + ""; //數(shù)字增加1 string filePath = System.Web.Hosting.HostingEnvironment.MapPath(testFilePath); System.IO.File.WriteAllText(filePath, newText, System.Text.Encoding.UTF8); return text; } }
4.測(cè)試頁面利用官方控件無刷新實(shí)現(xiàn)文件數(shù)字顯示
(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"; } }}
實(shí)現(xiàn)效果:
源代碼:TimedTask.zip
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注