直接上源码:简单粗暴。
原理就是根据System.Timers.Timer定时每秒触发事件。
using System;
using System.Timers;
public class TimerClass
{
private Timer timer;
private int iHour = 00;
private int iMinute = 00;
private int iSecond = 00;
private static readonly TimerClass tc = new TimerClass();
public static TimerClass GetInstance() {
return tc;
}
private TimerClass() {
timer = new Timer();
timer.Interval = 1000;
timer.Elapsed += Timer_Elapsed;
timer.Enabled = true;
Console.WriteLine("计时器初始化完成");
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
int intHour = e.SignalTime.Hour;
int intMinute = e.SignalTime.Minute;
int intSecond = e.SignalTime.Second;
DateTime dt = e.SignalTime;
if (iHour == intHour &&
iMinute == intMinute &&
iSecond == intSecond)
{
Console.WriteLine("00:00:00触发");
}
if (iMinute == intMinute && iSecond == intSecond)
{
Console.WriteLine("整点时触发的!!!");
}
if (iSecond == intSecond)
{
Console.WriteLine("每分钟触发的!!!");
}
Console.WriteLine("每秒触发的!!!");
Console.WriteLine("当前时间!!=" + dt.ToString("hh-mm-ss"));
}
public void Stop() {
timer.Stop();
}
public void Start()
{
timer.Start();
}
}