0
点赞
收藏
分享

微信扫一扫

C#中实现计时器功能(定时任务和计时多长时间后执行某方法)

快乐小码农 2023-02-15 阅读 40


场景

在低液位预警弹窗点击确定后需要实现一个计时器,比如在五分钟后再执行监控。

实现思路是使用Timer然后每秒执行一个方法,在方法中对秒数进行减1操作,等倒计时结束后执行相应的操作。

注:

实现

但是Timer有三个

1.定义在System.Windows.Forms里  
2.定义在System.Threading.Timer类里  
3.定义在System.Timers.Timer类里

一开始使用的是System.Windows.Forms里面的

System.Windows.Forms.Timer是应用于WinForm中的,它是通过Windows消息机制实现的,类似于VB或Delphi中的Timer控件,内部使用API  SetTimer实现的。它的主要缺点是计时不精确,而且必须有消息循环,Console  Application(控制台应用程序)无法使用。

使用代码示例:

新建定时器类对象

System.Windows.Forms.Timer _timer = new System.Windows.Forms.Timer();

设置执行的间隔时间,单位毫秒

_timer.Interval = 1000;

设置间隔时间内执行的方法

_timer.Tick +=_timer_Tick;

private void _timer_Tick(object sender, EventArgs e)
{
//执行的业务
}

启动计时器

_timer.Start();

停止计时器

_timer.Stop();

 

但是发现此定时器并不执行,其每秒执行一次的方法不执行,原来其在控制台程序中没法使用

所以改为了System.Timers.Timer

新建定时器对象并设置执行的间隔时间为1秒

System.Timers.Timer _timerWaterTank = new System.Timers.Timer(1000);//实例化Timer类,设置间隔时间为1000毫秒;

 设置定时器的执行事件

_timerWaterTank.Elapsed += new System.Timers.ElapsedEventHandler(_timerWaterTank_Tick);//到达时间的时候执行事件;

设置是执行一次还是一直执行

_timerWaterTank.AutoReset = true;//设置是执行一次(false)还是一直执行(true);

具体执行的事件方法

private void _timerWaterTank_Tick(object sender, EventArgs e)
{
System.Timers.Timer timer = sender as System.Timers.Timer;
//要计时的时间秒数
this.LowLevelSecondsWaterTank--;
if (this.LowLevelSecondsWaterTank <= 0)
{
//倒计时结束后执行的业务
Global.PublicVar.Instance.IsGoOnMonitorWaterPool = true;
timer.Enabled = false;
this.LowLevelSecondsWaterTank = Global.LOW_LEVEL_MONITOR_SECONDS;

}
}

这样让定时器一秒执行一次方法,在此方法中将秒数减1,这样在秒数到0的时候执行具体的业务。

启动定时器

timer.Enabled = true;

停止计时器

timer.Enabled = false;

 

举报

相关推荐

0 条评论