1. 程式人生 > >c# Timer event 定時器事件

c# Timer event 定時器事件

1 簡介

實現定時器事件,每隔一個時間後觸發事件。

2.原理

2.1 名稱空間

using System.Timers;

2.2 宣告定時器

private Timer aTimer;

2.3 例項化定時器並設定屬性

 // Create a timer and set a two second interval.
        aTimer = new System.Timers.Timer();
        aTimer.Interval = 2000;

        // Hook up the Elapsed event for the timer. 
aTimer.Elapsed += OnTimedEvent; // Have the timer fire repeated events (true is the default) aTimer.AutoReset = true; // Start the timer aTimer.Enabled = true;

2.4 事件函式

時間函式的函式名要與註冊事件語句中的函式名要一致。

    private static void OnTimedEvent(Object source, System.
Timers.ElapsedEventArgs
e) { Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime); }

3.程式碼示例

using System;
using System.Timers;

public class Example
{
    private static Timer aTimer;

    public static void Main()
    {
        // Create a timer and set a two second interval.
aTimer = new System.Timers.Timer(); aTimer.Interval = 2000; // Hook up the Elapsed event for the timer. aTimer.Elapsed += OnTimedEvent; // Have the timer fire repeated events (true is the default) aTimer.AutoReset = true; // Start the timer aTimer.Enabled = true; Console.WriteLine("Press the Enter key to exit the program at any time... "); Console.ReadLine(); } private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e) { Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime); } } // The example displays output like the following: // Press the Enter key to exit the program at any time... // The Elapsed event was raised at 5/20/2015 8:48:58 PM // The Elapsed event was raised at 5/20/2015 8:49:00 PM // The Elapsed event was raised at 5/20/2015 8:49:02 PM // The Elapsed event was raised at 5/20/2015 8:49:04 PM // The Elapsed event was raised at 5/20/2015 8:49:06 PM