Double fire

I used some ex from stackoverflow, but sometimes my timer worked twice: this clock should fire every minute, but just assume that it shoots 00: 00: 59.666 then step1 = 59; step2 = 59; step3 = 1; return (1000-666); so he should not shoot the next minute, but the next 333 miles a second, what can I do?

public int SyncTime = 60; Clock = new System.Timers.Timer {AutoReset = false}; Clock.Elapsed += DoJob; Clock.Interval = GetSync(SyncTime); Clock.Start() private void DoJob(object sender, ElapsedEventArgs elapsedEventArgs) { Clock.Interval = GetSync(SyncTime); Clock.Start(); } private static double GetSync(int syncTime) { DateTime now = DateTime.Now; int step1 = (now.Minute * 60 + now.Second); //amount of miliseconds in this hour int step2 = step1 % syncTime; //amount of miliseconds since last update int step3 = syncTime - step2; //amount of miliseconds to next upadte return (step3 * 1000 - now.Millisecond); } 
0
source share
2 answers

I suspect the problem is on the line:

 Clock = new System.Timers.Timer {AutoReset = false}; 

I think this should read:

 Clock = new System.Timers.Timer {AutoReset = true}; 

This means that the timer will only fire once until you reissue the Start command.

0
source

Not sure if this is the answer to your specific problem, but the GetSync function calculates the remaining time up to a full minute.

This should be (if I haven't missed something, which is entirely possible):

 private static double GetSync(int syncTime) { DateTime now = DateTime.Now; return ((2 * syncTime) - now.Second) * 1000) - now.Millisecond; } 

This may solve your problem, since calculating the remaining time this way will never return 0 from GetSync.

EDIT: Incorrect calculation added 2 * synchronization time, which will calculate it correctly if I understand it correctly.

0
source

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


All Articles