定时器的使用说明

您所在的位置:网站首页 定时器的使用说明书图片 定时器的使用说明

定时器的使用说明

2024-07-11 20:46| 来源: 网络整理| 查看: 265

Net框架下有多种定时器,下面是其中两种使用的说明

一、system.timers.timer

1、普通使用,每隔一段时间执行一次,缺点:如果执行任务时间大于间隔时间,会造成多次启动定时器

private void Start() {

System.Timers.Timer oTimer = new System.Timers.Timer(60 * 60 * 1000); oTimer.Elapsed += new ElapsedEventHandler(AmWork); oTimer.AutoReset = true; oTimer.Enabled = true;

}

public void AmWork(object source, ElapsedEventArgs e) {Console.WriteLine("I'm working."); }

2、防止多次启动使用,执行的时候,停止定时器,执行完毕之后,开启定时器

public void Start() { System.Timers.Timer oTimer = new System.Timers.Timer(2*1000); Action amWork = (sender, e) => { oTimer.Stop(); Console.WriteLine("working:" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")); System.Threading.Thread.Sleep(5000); oTimer.Start(); }; oTimer.Elapsed += new System.Timers.ElapsedEventHandler(amWork); oTimer.AutoReset = true; oTimer.Enabled = true;

}

二、System.Threading.Timer定时器:不但可以设置间隔时间,也可以设置第一次执行间隔时间,有助于程序启动时,自定义第一次执行间隔时间

注意:只要在使用Timer,就必须保留对它的引用,可以理解为“timer需要定义为类的成员变量,而不是某方法的局部变量,否则会被回收”,但如果使用类没有实例化静态变量,也会导致回收掉1、普通使用

System.Threading.Timer timer = null;Action timerHandler = state =>{Console.WriteLine("working:" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));};

timer = new System.Threading.Timer(new System.Threading.TimerCallback(timerHandler), null, 1000, 2000);

2、防止多次启动使用,但使用了Change之后,change执行间隔时间,必须使用第一次执行时间,好像有点问题

System.Threading.Timer timer = null; Action timerHandler = state => { timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); //可防止上次任务没有执行完毕,重启计时器 Console.WriteLine("working:" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")); timer.Change(3000, 3000); };

timer = new System.Threading.Timer(new System.Threading.TimerCallback(timerHandler), null, 1000, 1000);



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3