编程就是这个样子

学的老,活到老
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

asp.net 网页定时器

Posted on 2008-12-29 22:53  寿  阅读(1022)  评论(0编辑  收藏  举报
public void Initaa()
  {  
 
   // 新建一个TimerCallback委托,具体要执行的方法在ScheduledWorkCallbackEmailInterval中 
   emailTimer = new Timer(new TimerCallback(ScheduledWorkCallbackEmailInterval), null, 5000, 2000);      
  } 
 
  /**//// <summary> 
  /// 释放定时器 
  /// </summary> 
  public void displose()
  { 
   statsTimer = null; 
   emailTimer = null; 
  } 
 
  /**//// <summary> 
  /// 定时任务
  /// </summary> 
  private void ScheduledWorkCallbackEmailInterval (object sender)
   { 
    try
    { 
     StreamWriter sw;
     string Path =  Server.MapPath(".");
     int last = Server.MapPath(".").LastIndexOf("\\");
      Path = Path.Substring(0,last)+"\\index.txt";
     if(!File.Exists(Path))
     {
      FileStream fs = File.Create(Path);
      sw = new StreamWriter(Path,false,System.Text.Encoding.GetEncoding("gb2312"));
     }
     else
     {
      sw = new StreamWriter(Path,true,System.Text.Encoding.GetEncoding("gb2312"));
     }
     sw.WriteLine("!");
     sw.WriteLine("!");
     sw.WriteLine("!");
     sw.WriteLine("------------"+DateTime.Now.ToString()+"----------------");
     sw.Close();
    } 
    catch
    { 
     Response.Write(2);
    } 
    finally
    { 
     emailTimer.Change( 5000, 5000 ); 
    } 
   } 
 
  //// <summary> 
  /// 定时休眠
  /// </summary> 
  private void ScheduledWorkCallbackStatsInterval(object sender)
  { 
   try
   { 
    // 休眠定时器 
    statsTimer.Change( System.Threading.Timeout.Infinite, 2000 ); 
     } 
   catch( Exception e )
   {
 
   } 
   finally
   { 
    // 唤醒定时器 
    statsTimer.Change( 5000, 2000); 
   } 
  } 

最后调用Initaa() 这个函数就可以了。作用是给文本文件中每个5秒写一次数据。