Tell me, please, how in C # can I run a method at a certain time? For example, every day at 14.00 it should be performed.

  • And the program is always running? =) - Alexey Sonkin
  • Yeah - Merlin

2 answers 2

The easiest and simplest way is to make a timer that fires once a minute and checks the time. As soon as coincidence - we cause. =)

if ((Hour == System.DateTime.Now.Hour) && (Minute == System.DateTime.Now.Minute)) { Nya(); } 

To call more often the meaning of special, I think, no.

  • Thanks you! The main thing that is simple and reliable. - Merlin
  • that I can’t understand how to set Hour and Minute without date - Merlin
  • Hour = 14; Minute = 00; So? = D - Alexey Sonkin
  • So, in short, I did :) <code> while (true) {int Hour = 23; int Minute = 42; int Seconds = 00; if ((Hour == System.DateTime.Now.Hour) && (Minute == System.DateTime.Now.Minute) && (Seconds == System.DateTime.Now.Second)) {MessageBox.Show ("Check") ; } System.Threading.Thread.Sleep (100); } </ code> - Merlin
  • Well, initialization can be pulled out of the loop - it never changes =) Yes, and sleep for a 100 ms stream - is it not enough? =) 9 checks out of 10 are superfluous (time does not change) =) - Alexey Sonkin
 private void SetTimer() { timer1.Stop(); var timeToAlarm = DateTime.Now.Date.AddHours(...).AddMinutes(...); if (timeToAlarm < DateTime.Now) timeToAlarm.AddDays(1); timer1.Interval = (int)(timeToAlarm - DateTime.Now).TotalMilliseconds; timer1.Start(); } 

and the timer will be called only at the right moment.

  • Interesting =) The current after the first operation will have to reconfigure, but this is a trifle. - Alexey Sonkin
  • Thanks, I copied my code for the future, just until I understand these timers and events ( - Merlin
  • SetTimer () and therefore a separate method, you need to call before starting and after the timer is triggered - Georgy