Timer.Elapsed属性自动定时处理程序
System.Timers.Timer
实例
直接在main方法中做定时调用 主要使用了 Timer.Elapsed属性
下面的示例实例化一个 System.Timers.Timer 对象,该对象 Timer.Elapsed 每两秒引发一次事件 (2000 毫秒) ,为事件设置事件处理程序,并启动计时器。
using System;
using System.Timers;
public class Example
{
private static System.Timers.Timer aTimer;
//用来定义定时器结束
static int count = 0;
public static void Main()
{
SetTimer();
}
private static void SetTimer()
{
// 设置二秒更新一次,这里面的2000参数就是aTimer.Interval,可直接设置也可放在参数中
aTimer = new System.Timers.Timer(2000);
// 根据Interval设定时间 引发事件
aTimer.Elapsed += OnTimedEvent;
//true为设置时间到期后自动重新执行 false只执行一次
aTimer.AutoReset = true;
//timer是否引发Elapsed事件 默认为false
aTimer.Enabled = true;
}
//执行类需要实现ElapsedEventHandler类
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
//需要定时实现代码块
count += 1;
if (count == 3)
{
//停止
_timer.Stop();
//释放由当前 Timer 使用的所有资源
_timer.Dispose();
}
}
}
浙公网安备 33010602011771号