开发者

timer fire twice

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(SyncTim开发者_运维知识库e);
            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);
    }


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜