1. 程式人生 > >C#使用Timer.Interval指定時間間隔與指定時間執行事件

C#使用Timer.Interval指定時間間隔與指定時間執行事件

https://www.cnblogs.com/wusir/p/3636149.html

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分這個時間節點,從而導致無法觸發該事件。