Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Timer (Bộ hẹn giờ) trong C#

Namespace System.Timers. Lớp Timer sinh sự kiện sau khoảng thời gian thiết lập, có tùy chọn lặp lại.

Tạo timer 5 giây:

timer = new System.Timers.Timer(5000);

Đăng ký sự kiện Elapsed:

timer.Elapsed += OnTimedEvent;

Bật timer:

timer.Enabled = true;

Ví dụ

using System;
using System.Timers;

public class Demo {
    private static Timer timer;
    public static void Main() {
        timer = new System.Timers.Timer();
        timer.Interval = 5000;
        timer.Elapsed += OnTimedEvent;
        timer.AutoReset = true;
        timer.Enabled = true;
        Console.WriteLine("Nhấn Enter để thoát...");
        Console.ReadLine();
    }
    private static void OnTimedEvent(Object source, ElapsedEventArgs e) {
        Console.WriteLine("Kích hoạt: {0}", e.SignalTime);
    }
}