C#实现定时器的三种方法 c# 定时器 cron

C#实现定时器的三种方法 c# 定时器 cron

编码文章call10242024-12-22 14:42:2633A+A-

在C#里关于定时器类就有三个

1、System.Windows.Forms.Timer

2、System.Threading.Timer

3、定义在System.Timers.Timer

下面对这三个类进行讲解。

System.Windows.Forms.Timer

计时器最宜用于 Windows 窗体应用程序中,并且必须在窗口中使用,适用于单线程环境,

在此环境中, UI 线程用于执行处理。它要求用户代码提供 UI 消息泵, 并且始终从同一线程操作, 或将调用封送到其他线程。Windows 窗体计时器组件是单线程的, 且限制为55毫秒的准确度,准确性不高。

private System.Windows.Forms.Timer timer;
 //创建定时器
 timer= new System.Windows.Forms.Timer();
 //设置定时器属性
timer.Tick+=new EventHandler(HandleTime);
timerGetTime.Interval = 1000;
timerGetTime.Enabled = true;
 //开启定时器
timerGetTime.Start();
public void HandleTime(Object myObject, EventArgs myEventArgs)
 {
 lbl_Time.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
 }
//停止定时器
 timerGetTime.Stop();

System.Timers.Timer

System.Timers.Timer t = new System.Timers.Timer(1000);//实例化Timer类,设置间隔时间为1000毫秒;
t.Elapsed += new System.Timers.ElapsedEventHandler(Execute);//到达时间的时候执行事件;
t.AutoReset = true;//设置是执行一次(false)还是一直执行(true);
t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件;
t.Start(); //启动定时器
//上面初始化代码可以写到构造函数中
public void Execute(object source, System.Timers.ElapsedEventArgs e)
{
 t.Stop(); //先关闭定时器
 MessageBox.Show("OK!");
t.Start(); //执行完毕后再开启器
}

System.Threading.Timer

线程计时器也不依赖窗体,是一种简单的、轻量级计时器,它使用回调方法而不是使用事件,并由线程池线程提供支持

class Program
 {
 int TimesCalled = 0;
 void Display(object state)
 {
 Console.WriteLine("{0} {1} keep running.", (string)state, ++TimesCalled);
 }
 static void Main(string[] args)
 {
 Program p = new Program();
 //2秒后第一次调用,每1秒调用一次
 System.Threading.Timer myTimer = new System.Threading.Timer(p.Display, "Processing timer event", 2000, 1000);
 // 第一个参数是:回调方法,表示要定时执行的方法,第二个参数是:回调方法要使用的信息的对象,或者为空引用,第三个参数是:调用 callback 之前延迟的时间量(以毫秒为单位),指定 Timeout.Infinite 以防止计时器开始计时。指定零 (0) 以立即启动计时器。第四个参数是:定时的时间时隔,以毫秒为单位
 Console.WriteLine("Timer started.");
 Console.ReadLine();
 }
}

喜欢请点个关注,谢谢大家支持;


点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4