三种Timer使用

Posted 1175429393wljblog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了三种Timer使用相关的知识,希望对你有一定的参考价值。

System.Windows.Forms.TimerSystem.Threading.Timer,  System.Timer,三种Timer使用如下

 

第一种:System.Windows.Forms.Timer使用

[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int SetWindowText(IntPtr hWnd, string text);

[DllImport("User32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll", EntryPoint = "FindWindowEx")]
private static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
/// <summary>
[DllImport("user32.dll", EntryPoint = "SendMessage")]
private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
const int WM_CLOSE = 0x10;
const int BM_CLICK = 0xF5;
int FunCord;
IntPtr hwnd;
int t;

System.Windows.Forms.Timer timer;

private void StartTimer(int interval)

Timer timer = new Timer();
timer.Interval = interval;
timer.Tick += new EventHandler(timer_Tick);
timer.Enabled = true;

private void timer_Tick(object sender, EventArgs e)

hwnd = FindWindow(null, t.ToString() + "秒后关闭");
t = t - 1;
SetWindowText(hwnd, t.ToString() + "秒后关闭");
if (t == 0)

timer.Enabled = false;

 

第二种:System.Threading.Timer使用

System.Threading.Timer   threadTimer = new System.Threading.Timer(new TimerCallback(TimerUp), null, Timeout.Infinite, 1000);
//立即开始计时,时间间隔1000毫秒
threadTimer.Change(0, 1000);

/// <summary>
/// 定时到点执行的事件
/// </summary>
/// <param name="value"></param>
private void TimerUp(object value)

try

timeOutValidate -= 1;

catch (Exception ex)

Program.Log.Error("执行定时到点事件失败:" + ex.Message);

 

第三种:System.Timer使用

System.Timers.Timer  timer = new System.Timers.Timer(interval);
timer.Elapsed += new System.Timers.ElapsedEventHandler(TimerTimeOut);
timer.Enabled = true;
timer.Start();
.
/// <summary>
/// Timer类执行定时到点事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TimerTimeOut(object sender, System.Timers.ElapsedEventArgs e)

try

timeOut -= 1;

catch (Exception ex)

Program.Log.Error("执行定时到点事件失败:" + ex.Message);

以上是关于三种Timer使用的主要内容,如果未能解决你的问题,请参考以下文章

NET中的三种Timer的区别和用法

C# 计时器的三种使用方法

android 三种定时器的写法

C#三种定时器的实现

(30)C# Timer类

Spring任务调度之Timer