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

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

0.先看解决方案截图

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

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

  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";
        }
    }
}
复制代码

实现效果:






本文转自叶超Luka博客园博客,原文链接:http://www.cnblogs.com/yc-755909659/p/5123944.html,如需转载请自行联系原作者
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值