在asp.net中要不使用其他插件的情况下只能使用定时器来检查, 并执行任务.
以下讲解步骤:
1. 在Global.asax 文件中作如下修改view sourceprint?01 | void Application_Start( object sender, EventArgs e) |
06 | System.Timers.Timer myTimer = new
System.Timers.Timer(1000); |
07 | //TaskAction.SetContent表示要调用的方法 |
08 | myTimer.Elapsed += new
System.Timers.ElapsedEventHandler(TaskAction.SetContent); |
09 | myTimer.Enabled = true ; |
10 | myTimer.AutoReset = true ; |
Application_Start 只有在访问一次之后才会触发.
view sourceprint?01 | void Session_End( object sender, EventArgs e) |
03 | //下面的代码是关键,可解决IIS应用程序池自动回收的问题 |
04 | System.Threading.Thread.Sleep(1000); |
06 | TaskAction.SetContent(); |
07 | //这里设置你的web地址,可以随便指向你的任意一个aspx页面甚至不存在的页面,目的是要激发Application_Start |
10 | System.Net.HttpWebRequest myHttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); |
11 | System.Net.HttpWebResponse myHttpWebResponse = (System.Net.HttpWebResponse)myHttpWebRequest.GetResponse(); |
12 | System.IO.Stream receiveStream = myHttpWebResponse.GetResponseStream(); //得到回写的字节流 |
15 | // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为 InProc 时,才会引发 Session_End 事件。 |
16 | // 如果会话模式设置为 StateServer |
17 | // 或 SQLServer,则不会引发该事件。 |
Session_End 中的方法主要是解决IIS应用程序池自动回收的问题.
2. 添加计划任务类 TaskActionview sourceprint?02 | using System.Collections.Generic; |
10 | public static class TaskAction |
12 | private static
string content =
"" ; |
16 | public static
string Content
|
18 | get { return TaskAction.content; } |
19 | set {TaskAction.content +=
"<div>" + value+ "</div>" ; } |
24 | /// <param name="source"></param> |
25 | /// <param name="e"></param> |
26 | public static
void SetContent( object source, ElapsedEventArgs e) |
28 | Content= DateTime.Now.ToString( "yyyy-MM-dd HH:mm:ss" ); |
33 | public static
void SetContent()
|
35 | Content= "END: "
+ DateTime.Now.ToString( "yyyy-MM-dd HH:mm:ss" ); |
3. 执行结果输出[Default.aspx] (此步仅仅为了观看结果才写的页面)
在Default.aspx页面 添加
view sourceprint?2 | <%=TaskAction.Content%> |
4. 结果输出
欢迎大家一起探讨
示例源代码下载