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

ASP.NET 中使用计时器执行用户代码

2006-12-30 14:07 441 查看
ASP.NET 中使用计时器执行用户代码
ASP.NET 中使用计时器执行用户代码 首先引入命名空间
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(); // 创建文件,定时执行此过程将不停的创建文件
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐