使用C#的Timer控制元件來實現定時觸發事件
阿新 • • 發佈:2019-02-03
使用C#的Timer控制元件來實現定時觸發事件,其主要引數如下:
Timer.Enabled 屬性用於設定是否啟用定時器
Timer.Interval 屬性,事件的間隔,單位毫秒
Timer.Elapsed 事件,達到間隔時發生
示例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Timers; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { System.Timers.Timer aTimer = new System.Timers.Timer(); aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); // Set the Interval to 5 seconds. aTimer.Interval = 5000; aTimer.Enabled = true; Console.WriteLine("Press /'q/' to quit the sample."); while (Console.Read() != 'q') ; } private static void OnTimedEvent(object source, ElapsedEventArgs e) { Console.WriteLine("Hello World!"); } } }