.

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
User avatar
SKAN
Posts: 1551
Joined: 29 Sep 2013, 16:58

Re: How to Run at Specific Time in Milliseconds?

17 Aug 2017, 19:44

GT77 wrote:I tried the script and I noticed that it always fires few houndreds milliseconds late, which means it can be as late as 999 milliseconds, which means it can be late almost a full second. Is it impossible to do using A_TickCount or other functions and NOT checking time constantly?
You don't have to check time constantly for the whole period of wait... just for a few 10s of ms.
Try this.

Code: Select all

T := A_Now
T += 1, Seconds
T .= ".500"
MsgBox % SleepTill( T )


SleepTill( Timestamp ) {
Local OTC := TC := A_TickCount, V := StrSplit( TimeStamp ".0", "." ), SleepMS := V.1     
  SleepMS -= A_Now, Seconds
  SleepMS := ( SleepMS * 1000 + V.2 )
  TC :=  TC + SleepMS
  Sleep, %SleepMS%
  While ( A_Tickcount < TC )
    Sleep -1
Return ( A_Tickcount - OTC ) / 1000
}

You could call it like.. for eg.

Code: Select all

SleepTill( 20170818054334.500 )
SetTimer, Alarm, -1
Should be precise to the nearest 32ms.
SleepTill() function can be be precise to 1ms if query performance counters are used. See AccuSleep()
My Scripts and Functions: V1  V2
just me
Posts: 9453
Joined: 02 Oct 2013, 08:51
Location: Germany

Re: How to Run at Specific Time in Milliseconds?

18 Aug 2017, 02:42

GT77 wrote:I noticed that it always fires few houndreds milliseconds late, which means it can be as late as 999 milliseconds, which means it can be late almost a full second.
The problem isn't the accuracy of Sleep/SetTimer, it's the calculation of DelayInMilliseconds/Period.

Code: Select all

TargetTime  := 20170818000010
CurrentTime := 20170818000000 ; replaces A_Now
TimeToWait := TargetTime
TimeToWait -= CurrentTime, Seconds
TimeToWait *= 1000 ; convert to milliseconds
MsgBox, %TimeToWait%
will always retrieve 10000 ignoring the milliseconds at calculation time.

If calculated at CurrentTime + 0 ms it will expire about TargetTime + 0 ms which is the wanted behaviour. But if calculated at CurrentTime + 999 ms it will expire about TargetTime + 999 ms which is correct but unwanted. You have to subtract the current milliseconds in a 'milliseconds until' calculation:

Code: Select all

TimeToWait *= 1000 ; convert to milliseconds
TimeToWait -= CurrentMSec ; subtract current milliseconds
BoBo
Posts: 6564
Joined: 13 May 2014, 17:15

Re: How to Run at Specific Time in Milliseconds?

18 Aug 2017, 07:48

You have to subtract the current milliseconds in a 'milliseconds until' calculation
Kinda A_TickCount/QueryPerformanceCounter scenario ?! ;)

https://autohotkey.com/board/topic/1090 ... r-example/
https://autohotkey.com/board/topic/4806 ... cecounter/

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: Holarctic, jameswrightesq, Lem2001 and 419 guests