Delphi Timer: Time before next event

前端 未结 2 1005
盖世英雄少女心
盖世英雄少女心 2020-12-11 15:59

Is it possible to determine when a TTimer in Delphi will trigger? I know how to calculate this based upon the timer\'s last run and the timers interval. Unfortunately, the

相关标签:
2条回答
  • 2020-12-11 16:00

    There's absolutely no way to query a Windows timer for information of this nature. You will simply have to keep track of this yourself.

    I would do this by wrapping up the TTimer with composition and not inheritance. You can then be sure that you will capture all modifications to the timer state.

    0 讨论(0)
  • 2020-12-11 16:20

    In this case I recommend you switch from a TTimer which uses Windows timers, to a thread based TTimer-style component. Then you can query the time until the next event.

    Alternative; If you want a simple ugly hack, then change your Timer interval to 1 second instead of 120 seconds, and do a countdown yourself:

       const
         CounterPreset = 120;
    
       ...
    
       procedure TForm1.FormCreate(Sender:TObject);
       begin
          FCounter := CounterPreset;
          Timer1.Interval := 1000;
          Timer1.Enabled := true;
       end;
    
       procedure TForm1.Timer1Timer(Sender);
       begin
               Dec(FCounter);
               if (FCounter<=0) then
               begin
                  DoRealTimerCodeHere;
                  FCounter := CounterPreset;
               end;
       end;
    
       function  TForm1.TimeLeft:Integer;
       begin
             result := FCounter;
       end;
    

    This will be inaccurate subject to the limitations of the WM_TIMER message, documented only vaguely at MSDN here. Real experience shows that WM_TIMER should only be used for things that don't need to happen at all, and should be used as a convenience, not as a hard-timing system.

    0 讨论(0)
提交回复
热议问题