您的位置:首页 > 编程语言 > ASP

Asp.net定时执行任务(定时器改良)

2012-07-20 13:43 330 查看
源码:点击下载源代码

在Global.asax的Application_Start的时候执行代码。

在这里遇到了一个问题,就是不能使用 HttpContext.Current.Server.MapPath("~/XXX.txt"); 会报错:空引用 !

后来谷歌了一下,找到好下解决方案:System.Web.Hosting.HostingEnvironment.MapPath("~/XXX.txt"); 代替,搞定!

原来的代码是网上找的(链接找不到了……),只能在一个类中写死,“改良”后的可以通过Default.aspx设置以后执行。

开始我用了一个模型层去存放设置的时间,后来发现不灵,因为程序最先加载Global.asax中的代码(如果你设置一个断点就能看出来),这个时候界面还没有加载,所以模型中的数据是空的,就算你设置完了也没有用,因为人家Global都执行过了。

没办法后来想了一个笨方法,就是通过Default.aspx页面,把设置的传写到一个txt文件中,当程序运行的时候从里面读取。这样就行了。

源码:点击下载源代码 http://www.cnblogs.com/zhuiyi/archive/2011/07/06/2098798.html

asp.net 利用 Global.asax 定时执行任务

1.在当前站点下添加Global.asax文件。

2.代码如下:

<%@ Application Language="C#" %>

<script runat="server">

void Application_Start(object sender, EventArgs e)

{

System.Timers.Timer timer = new System.Timers.Timer(1000);

timer.Elapsed += new System.Timers.ElapsedEventHandler(writelog);

timer.Start();

}

protected void writelog(object sender, System.Timers.ElapsedEventArgs e)

{

//check datetime, Do the job on 12:00 everyday.

if (DateTime.Now.Hour == 12 && DateTime.Now.Minute == 0)

{

string logdate = DateTime.Now.ToString("yy-MM-dd");

string logfilename = logdate + ".log";

string loglist = DateTime.Now.ToString();

if (System.IO.File.Exists(logfilename))

{

System.IO.StreamWriter swobj = System.IO.File.AppendText("C:\\" + logfilename);

swobj.WriteLine(loglist);

swobj.Flush();

swobj.Close();

}

else

{

System.IO.StreamWriter swobj = System.IO.File.CreateText("C:\\" + logfilename);

swobj.WriteLine(loglist);

swobj.Flush();

swobj.Close();

}

}

}

</script>
http://kms.lenovots.com/kb/article.php?id=9226
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: