NET开发日记11

用C#限时

首先引入命名空间
using System.Timers;
using System.IO;

在 Global.asax 中加入静态对象(变量)
public static Timer gtimer = null;  // 定义全局定时器类对象
public static int gcount = 0;  //  测试用计时器变量

在 Global.asax 中的 Application_OnStart 事件过程中定义计时器,代码如下:
protected void Application_Start(Object sender, EventArgs e)
  {
    // 创建一个计时器,单位:毫秒
    gtimer = new Timer(1000);
    // 将自定义用户函数(TimerEventFunction)指定为计时器的 Elapsed 事件处理程序
    // TimerEventFunction 可以写入自己的需要执行的代码逻辑
    gtimer.Elapsed += new System.Timers.ElapsedEventHandler(this.TimerEventFunction);
    // AutoReset 属性为 true 时,每隔指定时间间隔触发一次事件
    // 若赋值 false,则只执行一次
    gtimer.AutoReset = true;
    gtimer.Enabled = true;
  }

  TimerEventFunction 函数代码如下:
    // 定时器定时触发控件
  protected void TimerEventFunction(Object sender, ElapsedEventArgs e)
  {
   // 这里写入自定义代码
   gcount += 1;
   FileInfo file = new FileInfo("C://" + gcount.ToString() + ".txt");
   file.Create();  //    创建文件,定时执行此过程将不停的创建文件
  }

posted on 2006-05-29 10:45  badyue  阅读(133)  评论(0编辑  收藏  举报

导航