In .NET, four standard timer classes are defined, each with its own characteristics. In your case, as correctly noted in the @vitidev comments, either System.Threading.Timer or System.Timers.Timer will do . On EnSO I found a link to a comparative article about timers: the answer to EnSO is an article in English (for non-English speakers, there is a comparative table of timers at the very end of the article). Also, the comparison of timers and their main purpose are given in the notes to the descriptions of classes, but there this description is rather modest.
I used System.Timers.Timer . The minimum usage example in the code below.
static void Main(string[] args) { using (Timer timer = new Timer()) { timer.Interval = 2000;//интервал задается в миллисекундах timer.Elapsed += timer_Elapsed; timer.Start(); //Ставим основной поток на ожидание, т.к. таймер исполняется в //отдельном потоке и не препятствует завершению основного потока. Console.ReadLine(); } } static void timer_Elapsed(object sender, ElapsedEventArgs e) { //тут пишем код, который должен выполняться по событию таймера. //в вашем случае это будет вызов метода записи в таблицу на сервере, //либо собственно код этого метода. Console.WriteLine(e.SignalTime); }
More detailed examples for both types of timers are contained in the class descriptions by reference at the beginning of the answer.
Of course, you can not just put the thread on hold, but perform other useful actions in the main thread while the timer is doing its job.
There is another solution to the problem. I can use a cycle with an exit by the counter or by pressing a key and Thread.Sleep to stop the main and only thread for a specified time interval, but this solution, despite its simplicity, does not seem to me a good one. When timer tasks are performed in separate threads, we can display additional information about the progress of tasks in the console, control the timer state and perform other actions. In the case of a single stream with pauses, we are deprived of freedom of maneuver; for the time of freezing the stream, the program simply stops responding to external stimuli and can only be closed forcibly.