timer fire twice

2019-08-26 20:36发布

问题:

i ve used some ex from stackoverflow but sometimes my timer fire twice: this clock should fire each one minute, but just assume that it fires 00:00:59.666 then step1 = 59; step2 = 59; step3 = 1; return (1000-666); so it should fire not next minute but next 333 mili 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);
    }

回答1:

I suspect that the issue is in the line:

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

I think this should read:

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

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



回答2:

Ok not sure if this is the answer to your specific issue but your GetSync function is calculating the remaining time till the full minute incorrectly.

It should be (unless I am missing something which is completely possible):

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

This may resolve your issue as calculating the remaining time this way will never result in you returning a 0 value from GetSync.

EDIT: Misunderstood the calculation added 2* the sync time which will calculate it properly now if I understand it correctly.



标签: c# timer