ASP.NET定时执行任务 (不使用外接程序,.net内部机制实现)
				
									
					
					
						|  | 
							Ccoffee 2024年8月1日 10:33
								本文热度 2580 | 
					
				 
				 :ASP.NET定时执行任务 (不使用外接程序,.net内部机制实现)
:ASP.NET定时执行任务 (不使用外接程序,.net内部机制实现)在asp.net中要不使用其他插件的情况下只能使用定时器来检查, 并执行任务.
以下讲解步骤:
1. 在Global.asax 文件中作如下修改
| 1 2 3 4 5 6 7 8 9 10 11 | voidApplication_Start(objectsender, EventArgs e) 
 {
     
     
     
     System.Timers.Timer myTimer = newSystem.Timers.Timer(1000);
     
     myTimer.Elapsed += newSystem.Timers.ElapsedEventHandler(TaskAction.SetContent);
     myTimer.Enabled = true;
     myTimer.AutoReset = true; 
 }
 | 
Application_Start 只有在访问一次之后才会触发.
 
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | voidSession_End(objectsender, EventArgs e) 
 {
     
     System.Threading.Thread.Sleep(1000);
     
     TaskAction.SetContent();
     
     
     System.Net.HttpWebRequest myHttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
     System.Net.HttpWebResponse myHttpWebResponse = (System.Net.HttpWebResponse)myHttpWebRequest.GetResponse();
     System.IO.Stream receiveStream = myHttpWebResponse.GetResponseStream();
       
     
     
     
 }
 | 
Session_End 中的方法主要是解决IIS应用程序池自动回收的问题.
 
2. 添加计划任务类 TaskAction
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | usingSystem;
 usingSystem.Collections.Generic;
 usingSystem.Linq;
 usingSystem.Web;
 usingSystem.Timers;
   /// <summary>
 ///Action 的摘要说明
 /// </summary>
 publicstaticclassTaskAction
 {
     privatestaticstringcontent = "";
     /// <summary>
     /// 输出信息存储的地方.
     /// </summary>
     publicstaticstringContent
     {
         get{ returnTaskAction.content; }
         set{ TaskAction.content += "<div>"+ value+"</div>"; }
     }
     /// <summary>
     /// 定时器委托任务 调用的方法
     /// </summary>
     /// <param name="source"></param>
     /// <param name="e"></param>
     publicstaticvoidSetContent(objectsource, ElapsedEventArgs e)
     {
         Content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
     }
     /// <summary>
     /// 应用池回收的时候调用的方法
     /// </summary>
     publicstaticvoidSetContent()
     {
         Content = "END: "+ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
     }
 }
 | 
3. 执行结果输出[Default.aspx] (此步仅仅为了观看结果才写的页面) 
在Default.aspx页面 添加
| 1 2 3 | <div>
     <%=TaskAction.Content %>
 </div>
 | 
 
4. 结果输出

欢迎大家一起探讨
原文地址:http://www.cnblogs.com/henw/archive/2011/09/23/2186239.html
该文章在 2024/8/1 10:34:00 编辑过