C#中,Timer是一個定時器,它可以按照指定的時間間隔或者指定的時間執行一個事件。
指定時間間隔是指按特定的時間間隔,如每1分鍾、每10分鍾、每1個小時等執行指定事件;
指定時間是指每小時的第30分、每天10:30:30(每天的10點30分30秒)等執行指定的事件;
在上述兩種情況下,都需要使用 Timer.Interval,方法如下:
1、按特定的時間間隔:
using System;
using System.Timers;
namespace TimerExample
{
class Program
{
static void Main(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Enabled = true;
timer.Interval = 600000; //執行間隔時間,單位為毫秒; 這里實際間隔為10分鍾
timer.Start();
timer.Elapsed += new System.Timers.ElapsedEventHandler(test);
Console.ReadKey();
}
private static void test(object source, ElapsedEventArgs e)
{
Console.WriteLine("OK, test event is fired at: " + DateTime.Now.ToString());
}
}
}
上述代碼,timer.Inverval的時間單位為毫秒,600000為10分鍾,所以,上代碼是每隔10分鍾執行一次事件test。注意這里是Console應用程序,所以在主程序Main中,需要有Console.Readkey()保持Console窗口不關閉,否則,該程序執行后一閃就關閉,不會等10分鍾的時間。
2、在指定的時刻運行:
using System;
using System.Timers;
namespace TimerExample1
{
class Program
{
static void Main(string[] args)
{
System.Timers.Timer timer = new System.Timers.Timer();
timer.Enabled = true;
timer.Interval = 60000;//執行間隔時間,單位為毫秒;此時時間間隔為1分鍾
timer.Start();
timer.Elapsed += new System.Timers.ElapsedEventHandler(test);
Console.ReadKey();
}
private static void test(object source, ElapsedEventArgs e)
{
if (DateTime.Now.Hour == 10 && DateTime.Now.Minute == 30) //如果當前時間是10點30分
Console.WriteLine("OK, event fired at: " + DateTime.Now.ToString());
}
}
上述代碼,是在指定的每天10:30分執行事件。這里需要注意的是,由於是指定到特定分鍾執行事件,因此,timer.Inverval的時間間隔最長不得超過1分鍾,否則,長於1分鍾的時間間隔有可能會錯過10:30分這個時間節點,從而導致無法觸發該事件。

