In C #, a timer is a timer that can execute an event at a specified time interval or at a specified time.
The specified time interval refers to the execution of specified events at a specific time interval, such as every 1 minutes, every 10 minutes, and every 1 hours.
The specified time is the 30th minute of every hour, daily 10:30:30 (10 points per day, 30 minutes, 30 seconds), etc. to perform the specified event;
In both cases, you need to use Timer.interval, as follows:
1, at a specific time interval:
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; Execution interval time, in milliseconds; Here the actual interval is 10 minutes 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 ());}}}
The above code, timer. The time unit for Inverval is milliseconds, 600000 is 10 minutes, so the code is executed every 10 minutes with the event test. Note that this is the console application, so in main program main, you need to have Console.readkey () to keep the console window from shutting down, otherwise, the program will be closed after a flash, not waiting for 10 minutes.
2. Run at the specified time:
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;//execution interval, in milliseconds, at which time interval is 1 minute timer. Start (); Timer. Elapsed + = new System.Timers.ElapsedEventHandler (test); Console.readkey (); } private static void Test (object source, Elapsedeventargs e) { if (DateTime.Now.Hour = = && DATETIME.N ow. Minute = =) //If the current time is 10:30 Console.WriteLine ("OK, Event fired at:" + DateTime.Now.ToString ());} }
The above code is the execution event at the specified 10:30 per day. It is important to note that because it is specified to perform the event to a specific minute, therefore, the timer. The time interval of the inverval must not exceed 1 minutes, otherwise, a time interval longer than 1 minutes may miss 10:30 minutes of this time node, causing the event to not be triggered.
C # Timer timed task