星空网 > 软件开发 > ASP.net

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

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

0.先看解决方案截图

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

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

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

【ASP.NET 进阶】定时执行任务实现 (定时读取和修改txt文件数字内容,无刷新显示结果)【ASP.NET 进阶】定时执行任务实现 (定时读取和修改txt文件数字内容,无刷新显示结果)
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 ="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";    }  }}

实现效果:

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

 

源代码:TimedTask.zip




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

关键词:ASP.NET

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

快递从中国到泰国要多久:https://www.goluckyvip.com/tag/103727.html
现在可以寄快递到泰国吗:https://www.goluckyvip.com/tag/103728.html
寄快递到泰国需要多久:https://www.goluckyvip.com/tag/103729.html
开发客户:https://www.goluckyvip.com/tag/10373.html
国内的快递可以发到泰国吗:https://www.goluckyvip.com/tag/103730.html
快递到泰国多少钱一斤:https://www.goluckyvip.com/tag/103731.html
推荐一个Youtube视频 摘要和核心内容 AI提取工具:https://www.kjdsnews.com/a/1842190.html
威海船票(威海到各地船票价格查询):https://www.vstour.cn/a/409228.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流