1. 程式人生 > 實用技巧 >C#定時器的用法

C#定時器的用法

關於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分開始執行!";
   }
  } 
}
} 
    }
}