關於C#中timer類 在C#里關於定時器類就有3個
1.定義在System.Windows.Forms里
2.定義在System.Threading.Timer類里
3.定義在System.Timers.Timer類里
System.Windows.Forms.Timer是應用於WinForm中的,他是通過Windows消息機制實現的,類似於VB或Delphi中的Timer控件,內部使用API SetTimer實現的。他的主要缺點是計時不精確,而且必須有消息循環,Console Application(控制台應用程式)無法使用。
System.Timers.Timer和System.Threading.Timer很類似,他們是通過.NET Thread Pool實現的,輕量,計時精確,對應用程式、消息沒有特別的需要。System.Timers.Timer還能夠應用於WinForm,完全取代上面的Timer控件。他們的缺點是不支持直接的拖放,需要手工編碼。
1.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Timers; using System.Collections; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { System.Timers.Timer aTimer = new System.Timers.Timer(); aTimer.Elapsed += new ElapsedEventHandler(theout); //到達時間的時候執行事件; // 設置引發時間的時間間隔 此處設置為1秒(1000毫秒) aTimer.Interval = 1000; aTimer.AutoReset = true;//設置是執行一次(false)還是一直執行(true); aTimer.Enabled = true; //是否執行System.Timers.Timer.Elapsed事件; } public void theout(object source, System.Timers.ElapsedEventArgs e) { ArrayList AutoTask = new ArrayList(); AutoTask.Add("8:30:00"); AutoTask.Add("9:30:00"); AutoTask.Add("10:30:00"); AutoTask.Add("11:34:15"); for (int n = 0; n < 4; n++) { if (DateTime.Now.ToLongTimeString().Equals(AutoTask[n])) { MessageBox.Show("現在時間是" + AutoTask[n]); } } }
2.
C#.net 定時器
最近需要用到一個定時器,設定當 程序 到某時刻 執行某段代碼。
using System; using System.Timers; namespace 定時器ConsoleApplication1 { class Class1 { [STAThread] static void Main(string[] args) { System.Timers.Timer aTimer = new System.Timers.Timer(); aTimer.Elapsed += new ElapsedEventHandler(TimeEvent); // 設置引發時間的時間間隔 此處設置為1秒(1000毫秒) aTimer.Interval = 1000; aTimer.Enabled = true; Console.WriteLine("按回車鍵結束程序"; Console.WriteLine(" 等待程序的執行......"; Console.ReadLine(); } // 當時間發生的時候需要進行的邏輯處理等 // 在這里僅僅是一種方式,可以實現這樣的方式很多. private static void TimeEvent(object source, ElapsedEventArgs e) { // 得到 hour minute second 如果等於某個值就開始執行某個程序。 int intHour = DateTime.Now..Hour; int intMinute = DateTime.Now.Minute; int intSecond = DateTime.Now.Second; // 定制時間; 比如 在10:30 :00 的時候執行某個函數 int iHour = 10; int iMinute = 30; int iSecond = 00; // 設置 每秒鍾的開始執行一次 if( intSecond == iSecond ) { Console.WriteLine("每秒鍾的開始執行一次!"; } // 設置 每個小時的30分鍾開始執行 if( intMinute == iMinute && intSecond == iSecond ) { Console.WriteLine("每個小時的30分鍾開始執行一次!"; } // 設置 每天的10:30:00開始執行程序 if( intHour == iHour && intMinute == iMinute && intSecond == iSecond ) { Console.WriteLine("在每天10點30分開始執行!"; } } } } } }