yessiree

Multiple independently timed executions

16 posts in this topic

#1 ·  Posted (edited)

I have an array of integers. These numbers represent seconds. The number of items in this array is user defined.

I want to loop through this array, read the integer value, and call a function that will execute once after {value} seconds.

Is there a way to do this via AdlibRegister() ?

 

#include <AutoItConstants.au3>
#include <Array.au3>

Example()

Func Example()
    Global $aArray[3] = [10, 5, 2]


    For $i = 0 To 2
        AdlibUnRegister("myFunc")
        AdlibRegister("myFunc", $aArray[$i])
    Next
    _ArrayDisplay($aArray)
EndFunc



Func myFunc()
    ConsoleWrite("TimeOut called")
EndFunc

 

Thanks in advance

Edited by yessiree

Share this post


Link to post
Share on other sites



The short answer is yessiree, but without any code/example I don't think you will get much help.

Share this post


Link to post
Share on other sites

The short answer is yessiree, but without any code/example I don't think you will get much help.

I added code, can you take a look

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

So you only have a single function not more than one?  That makes it easy.

The code you posted looks like it should work to me, just keep in mind its milliseconds so your going to want to make those way bigger integer values ;)

The other thing I see is you have nothing to keep the script running in that example so it would register the function and then close.

You need this somewhere

While 1
Sleep(10)
WEnd

 

Edited by ViciousXUSMC

Share this post


Link to post
Share on other sites

Take a look at the adlibregister doc.  When you define the same func it is reset to the new timer value.  You might be able to do this by sorting the array and keeping track of intervals to the next call but it would be easier to implement an array of timers based on the array of timing values inputed by the user.  I cant work up any code right now as i am responding from a phone.

 


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

Take a look at the adlibregister doc.  When you define the same func it is reset to the new timer value.  You might be able to do this by sorting the array and keeping track of intervals to the next call but it would be easier to implement an array of timers based on the array of timing values inputed by the user.  I cant work up any code right now as i am responding from a phone.

 

Thanks for the input, I'll try to see where I can go with this

Share this post


Link to post
Share on other sites
#include <AutoItConstants.au3>
#include <Array.au3>

Global $aArray[3] = [10, 5, 2]
Global $timerActive[3] = [0,0,0]
Global $timer[3]

AdlibRegister("myFunc", 500)

Example()

Func Example()
    While 1
        For $i = 0 To 2
            If $timerActive[$i] == 0 Then
                $timerActive[$i] = 1
                $timer[$i] = TimerInit()
            EndIf
        Next
        Sleep(50)
    WEnd
    _ArrayDisplay($aArray)
EndFunc

Func myFunc()
    For $j = 0 To 2
        if $timerActive[$j] == 1 Then
            If Int(TimerDiff($timer[$j])) >= $aArray[$j]*1000 Then
                $timerActive[$j] = 0
            EndIf
        EndIf
    Next
EndFunc

So I figured out how to do it. But I still can't figure out why this language doesn't have a setTimeout() function :P

Share this post


Link to post
Share on other sites
So I figured out how to do it. But I still can't figure out why this language doesn't have a setTimeout() function

What are you looking for that's not available in the language now? What does the settimeout function do that one of the functions already in the language not do now?


If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites

What are you looking for that's not available in the language now? What does the settimeout function do that one of the functions already in the language not do now?

Well, instead of implementing timers and watchers that unnecessarily complicate your program, or calling Sleep() that blocks the main thread, you have a reliable function that does something after a fixed amount of time has passed?

Share this post


Link to post
Share on other sites

yessiree,

I do not call this complicated:

HotKeySet("{ESC}", "_Exit")
Func _Exit()
    Exit
EndFunc



; Set up the functions to run just once
Func _Func_0()
    ; Cancel Adlib
    AdlibUnRegister(_Func_0)
    ; Run code
    ConsoleWrite("Func_0 called at " & @SEC & @CRLF)
EndFunc



Func _Func_1()
    AdlibUnRegister(_Func_1)
    ConsoleWrite("Func_1 called at " & @SEC & @CRLF)
EndFunc



Func _Func_2()
    AdlibUnRegister(_Func_2)
    ConsoleWrite("Func_2 called at " & @SEC & @CRLF)
EndFunc



; Create array holding delay times and associated functions
Global $aArray[3][2] = [[10, _Func_0], [5, _Func_1], [2, _Func_2]]

; Set the Adlibs
For $i = 0 To 2
    AdlibRegister($aArray[$i][1], $aArray[$i][0] * 1000)
Next

ConsoleWrite("Started at " & @SEC & @CRLF)

While 1
    Sleep(10)
WEnd

3 functions, one array and a setting loop - hardly onerous.

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

Share this post


Link to post
Share on other sites

Or even this using _Timer_SetTimer

#include <GUIConstantsEx.au3>
#include <GuiStatusBar.au3>
#include <ProgressConstants.au3>
#include <Timers.au3>
#include <WindowsConstants.au3>

Global $g_idMemo, $g_hStatus, $g_idProgress, $g_iPercent = 0, $g_iDirection = 1

_Example_CallBack()

Func _Example_CallBack()
    Local $hGUI, $iTimerProgress, $idChange, $iWait = 10, $idState
    Local $aParts[3] = [75, 330, -1]

    $hGUI = GUICreate("Timers Using CallBack Function(s)", 400, 320)
    $g_idMemo = GUICtrlCreateEdit("", 2, 32, 396, 226, BitOR($WS_HSCROLL, $WS_VSCROLL))
    GUICtrlSetFont($g_idMemo, 9, 400, 0, "Courier New")
    $idState = GUICtrlCreateButton("Start Progress Bar", 70, 270, 100, 25)
    $idChange = GUICtrlCreateButton("Change", 215, 270, 90, 25)
    GUICtrlSetState($idChange, $GUI_DISABLE)
    $g_hStatus = _GUICtrlStatusBar_Create($hGUI, $aParts)
    _GUICtrlStatusBar_SetText($g_hStatus, "Timers")
    _GUICtrlStatusBar_SetText($g_hStatus, @TAB & @TAB & StringFormat("%02d:%02d:%02d", @HOUR, @MIN, @SEC), 2)
    $g_idProgress = GUICtrlCreateProgress(0, 0, -1, -1, $PBS_SMOOTH)
    GUICtrlSetColor($g_idProgress, 0xff0000)
    _GUICtrlStatusBar_EmbedControl($g_hStatus, 1, GUICtrlGetHandle($g_idProgress))
    GUISetState(@SW_SHOW)

    _Timer_SetTimer($hGUI, 1000, "_UpdateStatusBarClock") ; create timer

    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                ExitLoop
            Case $idState
                If GUICtrlRead($idState) = "Start Progress Bar" Then
                    $iTimerProgress = _Timer_SetTimer($hGUI, $iWait, "_UpdateProgressBar") ; create timer
                    If @error Or $iTimerProgress = 0 Then ContinueLoop
                    GUICtrlSetData($idState, "Stop Progress Bar")
                    GUICtrlSetState($idChange, $GUI_ENABLE)
                Else
                    GUICtrlSetState($idChange, $GUI_DISABLE)
                    _Timer_KillTimer($hGUI, $iTimerProgress)
                    GUICtrlSetData($idState, "Start Progress Bar")
                EndIf

            Case $idChange
                If $iWait = 10 Then
                    $iWait = 250
                Else
                    $iWait = 10
                EndIf
                MemoWrite("Timer for _UpdateProgressBar set at: " & $iWait & " milliseconds")
                $iTimerProgress = _Timer_SetTimer($hGUI, $iWait, "", $iTimerProgress) ; reuse timer with different interval
        EndSwitch
    WEnd
    ConsoleWrite("Killed All Timers? " & _Timer_KillAllTimers($hGUI) & @CRLF) ; must be True as the timer to "_UpdateStatusBarClock" have not been killed
    GUIDelete()
EndFunc   ;==>_Example_CallBack

; call back function
Func _UpdateStatusBarClock($hWnd, $iMsg, $iIDTimer, $iTime)
    #forceref $hWnd, $iMsg, $iIDTimer, $iTime
    _GUICtrlStatusBar_SetText($g_hStatus, @TAB & @TAB & StringFormat("%02d:%02d:%02d", @HOUR, @MIN, @SEC), 2)
EndFunc   ;==>_UpdateStatusBarClock

; call back function
Func _UpdateProgressBar($hWnd, $iMsg, $iIDTimer, $iTime)
    #forceref $hWnd, $iMsg, $iIDTimer, $iTime
    $g_iPercent += 5 * $g_iDirection
    GUICtrlSetData($g_idProgress, $g_iPercent)
    If $g_iPercent = 100 Or $g_iPercent = 0 Then $g_iDirection *= -1
    If $g_iPercent = 100 Then
        GUICtrlSetColor($g_idProgress, 0xff0000)
    ElseIf $g_iPercent = 0 Then
        GUICtrlSetColor($g_idProgress, 0x0000ff)
    EndIf
EndFunc   ;==>_UpdateProgressBar

; Write a line to the memo control
Func MemoWrite($sMessage)
    GUICtrlSetData($g_idMemo, $sMessage & @CRLF, 1)
EndFunc   ;==>MemoWrite

 


If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites

yessiree,

I do not call this complicated:

3 functions, one array and a setting loop - hardly onerous.

M23

M23, I only used 3 functions for the sake of a simple example. In practice, the number of array elements is user defined. How would you dynamically declare the function callbacks if that's the case?

Share this post


Link to post
Share on other sites

yessiree,

if the user defines the number of functions to call, how are the functions themselves determined? I can only imagine that they are already present in the script - in which case the user just chooses the function to run when setting the time, possibly via a combo.

Perhaps if you gave some details of what exactly you are trying to do we might be able to offer more focused help - at the moment we can only offer generalities.

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

Share this post


Link to post
Share on other sites

#14 ·  Posted (edited)

yessiree,

if the user defines the number of functions to call, how are the functions themselves determined? I can only imagine that they are already present in the script - in which case the user just chooses the function to run when setting the time, possibly via a combo.

Perhaps if you gave some details of what exactly you are trying to do we might be able to offer more focused help - at the moment we can only offer generalities.

M23

Hi M23,

Okay, I have a 2D array that looks like this

;
;   BIND    CD  isOnCD
;   5       10  0
;   6       5   0
;   7       2   0

BIND is the keybind to be pressed, and CD (cooldown) dictates how often the corresponding key needs to be pressed, and isOnCD is a flag that indicates whether this key is on cooldown. This array is sorted based on CD, from longest to shortest.

The program loops through this array indefinitely. If the key is off cooldown, it is pressed, and isOnCD is set to 1, else, move on to the next key. Here is when the timers come in. If there was a setTimeout() function, after the key is pressed, I simply call setTimeout() and set its isOnCD flag back to 0 after CD seconds.

Hope my explanation makes sense. I just started using autoIt yesterday so I don't know what would be the best approach for this kind of stuff. Any suggestions are appreciated.

Edited by yessiree

Share this post


Link to post
Share on other sites

yessiree,

That simplifies things a lot:

HotKeySet("{ESC}", "_Exit")

; Create array holding binds, delay times and associated timestamps
Global $aArray[3][3] = [[5, 10, TimerInit()], [6, 5, TimerInit()], [7, 2, TimerInit()]]

ConsoleWrite("Started at " & @SEC & @CRLF)

While 1
    ; Check the timer
    For $i = 0 To UBound($aArray) - 1
        If TimerDiff($aArray[$i][2]) > ($aArray[$i][1] * 1000) Then
            ; Reset timestamp
            $aArray[$i][2] = TimerInit()
            ; Do what you need
            ConsoleWrite("Bind " & $aArray[$i][0] & " fired at " & @SEC & @CRLF)
        EndIf

    Next
WEnd



Func _Exit()
    Exit
EndFunc

And I get: this returned

Started at 44         5   6   7
Bind 7 fired at 46            46 
Bind 7 fired at 48            48
Bind 6 fired at 49        49
Bind 7 fired at 50            50 
Bind 7 fired at 52            52
Bind 5 fired at 54    54
Bind 6 fired at 54        54
Bind 7 fired at 54            54
Bind 7 fired at 56            56
Bind 7 fired at 58            58
Bind 6 fired at 59        59
Bind 7 fired at 00            00
Bind 7 fired at 02            02
Bind 5 fired at 04    04
Bind 6 fired at 04        04
Bind 7 fired at 04            04
Bind 7 fired at 06            06

Required gap          10  05  02

which looks just what you wanted.

M23

1 person likes this

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

Share this post


Link to post
Share on other sites

M23 - nice just what i had in mind in post #6

 


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now