【ASP.NET进阶】定时执行任务实现(定时读取和修改txt文件数字内容,无刷新显示结果)

王朝学院·作者佚名  2016-08-28
窄屏简体版  字體: 小  |  中  |  大  |  超大  

现在有很多网站或系统需要在服务端定时做某件事情,如每天早上8点半清理数据库中的无效数据等等,Demo 具体实现步骤如下:

0.先看解决方案截图

[flash=500,400]http://s1.knowsky.com/20160211/gyferxbpxq011.png[/flash]

1.创建asp.net项目TimedTask,然后新建一个全局应用程序类文件 Global.asax

2.然后在application_Start 事件中 启动定时器,如需要每隔多少秒来做一件事情,即在后台执行,与客户端无关,即使客户端全部都关闭,那么后台仍然执行,具体代码如下:

[flash=500,400]http://s1.knowsky.com/20160211/pzvrcp0h4c011.gif[/flash][flash=500,400]http://s1.knowsky.com/20160211/du5v1dor53z11.gif[/flash]usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Net;usingSystem.Threading;usingSystem.Timers;usingSystem.Web;usingSystem.Web.Security;usingSystem.Web.sessionState;namespaceTimedTask

{publicclassGlobal : System.Web.HttpApplication

{PRivatevoidAddCount(objectsender, ElapsedEventArgs e)

{//在这里编写需要定时执行的逻辑代码FileControl.ChangeFileNumber();

}protectedvoidApplication_Start(objectsender, EventArgs e)

{

System.Timers.Timer timer=newSystem.Timers.Timer();//AddCount是一个方法,此方法就是每个1秒而做的事情timer.Elapsed +=newSystem.Timers.ElapsedEventHandler(AddCount);

timer.Interval=1000;//设置引发时间的时间间隔,此处设置为1秒timer.Enabled =true;

timer.AutoReset=true;

}protectedvoidSession_Start(objectsender, EventArgs e)

{//在新会话启动时运行的代码}protectedvoidApplication_BeginRequest(objectsender, EventArgs e)

{

}protectedvoidApplication_AuthenticateRequest(objectsender, EventArgs e)

{

}protectedvoidApplication_Error(objectsender, EventArgs e)

{//在出现未处理的错误时运行的代码}protectedvoidSession_End(objectsender, EventArgs e)

{//在会话结束时运行的代码//注意: 只有在 Web.config 文件中的 sessionstate 模式设置为 InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer 或 SQLServer,则不会引发该事件}protectedvoidApplication_End(objectsender, EventArgs e)

{//在应用程序关闭时运行的代码//下面的代码是关键,可解决IIS应用程序池自动回收的问题//局限性:可以解决应用程序池自动或者手动回收,但是无法解决IIS重启或者web服务器重启的问题,当然这种情况出现的时候不多,而且如果有人访问你的网站的时候,又会自动激活计划任务了。Thread.Sleep(1000);//这里设置你的web地址,可以随便指向你的任意一个aspx页面甚至不存在的页面,目的是要激发Application_Startstringurl ="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文件实现:

publicclassFileControl

{privateconststringtestFilePath ="~/testfile.txt";publicstaticstringGetFileNumber()

{//获得物理路径stringfilePath = System.Web.Hosting.HostingEnvironment.MapPath(testFilePath);stringtext =System.IO.File.ReadAllText(filePath);returntext;

}publicstaticstringChangeFileNumber()

{stringtext =GetFileNumber();stringnewText = (int.Parse(text) +1) +"";//数字增加1stringfilePath =System.Web.Hosting.HostingEnvironment.MapPath(testFilePath);

System.IO.File.WriteAllText(filePath, newText, System.Text.Encoding.UTF8);returntext;

}

}

4.测试页面利用官方控件无刷新实现文件数字显示

(1) Html代码

<!DOCTYPE html><htmlxmlns="http://www.w3.org/1999/xhtml"><headrunat="server"><metahttp-equiv="Content-Type"content="text/html; charset=utf-8"/><title>Test</title></head><body><formid="form1"runat="server"><div><inputid="txtValue"type="text"/><asp:ScriptManagerID="ScriptManager1"runat="server"></asp:ScriptManager><asp:UpdatePanelID="UpdatePanel1"runat="server"><ContentTemplate><asp:TimerID="Timer1"runat="server"Interval="1000"OnTick="Timer1_Tick"></asp:Timer><asp:LabelID="lb_Value"runat="server"Text="1"></asp:Label></ContentTemplate></asp:UpdatePanel></div></form></body></html>

(2)cs 代码

namespaceTimedTask

{publicpartialclassTestForm : System.Web.UI.Page

{protectedvoidPage_Load(objectsender, EventArgs e)

{if(!IsPostBack)

{

TimeStart();

}

}protectedvoidTimer1_Tick(objectsender, EventArgs e)

{

TimeStart();

}privatevoidTimeStart()

{

lb_Value.Text="Runtime:"+ FileControl.GetFileNumber() +"s";

}

}

}

实现效果:

[flash=500,400]http://s1.knowsky.com/20160211/wdvutaqav0k11.gif[/flash]

源代码:TimedTask.zip

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航