Question about timers and variable intervals

The point of this timer is to execute some code whenever it is midnight. Thus, basically, the first interval will be between Now and until midnight, and all intervals following this will be 24 hours.

Now that everything is fine and good, but I was wondering how this timer works. Is MyTimer.Interval recounted every time the timer is reset?

System.Timers.Timer MyTimer = new System.Timers.Timer();
MyTimer.Elapsed += new ElapsedEventHandler(TriggeredMethod);
MyTimer.Interval = [pseudocode]Time between now and midnight[/pseudocode];
MyTimer.Start();

EDIT:

I'm having trouble adjusting the spacing inside my TriggerMethod. Where / how should I start the timer so that I don't get any context errors?

private void Form1_Load(object sender, EventArgs e)
{
System.Timers.Timer MyTimer = new System.Timers.Timer();
MyTimer.Elapsed += new ElapsedEventHandler(TriggeredMethod);
MyTimer.Start();
}

private void TriggerMethod(object source, ElapsedEventArgs e)
{
MyTimer.Interval = [pseudocode]Time between now and midnight[/pseudocode];
}
+3
source share
3 answers

A property Intervalis the number of milliseconds between timer calls.

, Interval Elapsed (int)(DateTime.Today.AddDays(1) - DateTime.Now).TotalMilliseconds.

Elapsed, , :

System.Timers.Timer MyTimer
private void Form1_Load(object sender, EventArgs e)
{
    MyTimer = new System.Timers.Timer();
    //...
}

, System.Timers.Timer .
Elapsed.
, System.Windows.Forms.Timer ( ) BeginInvoke.

+4

, ; , .

.

+1

Make your timer fire once an hour, and then do the actual work at midnight. And I also recommend using BeginInvoke to move the actual user interface interaction with the GUI thread.

0
source

Source: https://habr.com/ru/post/1750306/


All Articles