timmy2

For this background task is AdlibRegister or just Sleep better?

8 posts in this topic

I'm writing a small prog that will run in the background and sound an alarm if a certain Gmail message arrives in an otherwise unused account.

My inclination is to use a simple While/WEnd loop with a 5 minute Sleep between checking for messages, but I've seen examples here of somewhat similar background tasks that employ AdlibRegister so I'm curious which method is the most reliable and least impactful on the CPU.  Below are two simple scripts that begin to do what I want and represent how I think this could be handled.

While/WEnd with Sleep

#include <CheckMail.au3>
Global $aReturn
Global $iEmails

While 1
    $aReturn = CheckMail("username", "password")
    $iEmails = @extended
    If $iEmails > 0 ExitLoop
    Sleep(300000)   ; check for new messages every 5 minutes
WEnd

;work with contents of $aReturn array that contains the new message(s) found

 

While/WEnd with Sleep and AdlibRegister

#include <CheckMail.au3>
Global $aReturn
Global $iEmails = 0

AdlibRegister('_CallCheckMail',300000) ; check for new messages every 5 minutes

While 1
    Sleep(500000)   ;  I had to put something here. Does higher the value = less CPU demand?
    If $iEmails > 0 ExitLoop
WEnd

;work with contents of $aReturn array that contains the new message(s) found

Func _CallCheckMail
    $aReturn = CheckMail("username", "password")
    $iEmails = @extended
    Return
EndFunc

 

Share this post


Link to post
Share on other sites



I know putting sleep in a loop is a good practice just to save cpu cycles.  

The main difference in my use/experience is you can keep running a script while Adlibregister does its thing in the background, almost like running a separate script.  While sleep puts everything on hold in the current script.

 

So if your script had other functions that you wanted to keep active and working Adlibregister would allow this, but if your script only has the one purpose, putting everything to sleep should work just as good and be lighter on resources. 

 

The best may be a combination of both.  Your loop with a small sleep (say 100-500ms) to keep the script "alive" with Adlibregister to call your function at the desired intervals. 

Share this post


Link to post
Share on other sites

    So if your script had other functions that you wanted to keep active and working Adlibregister would allow this

The best may be a combination of both.  Your loop with a small sleep (say 100-500ms) to keep the script "alive" with Adlibregister to call your function at the desired intervals. 

Thank you for replying. You make an excellent point about when AdlibRegister is most appropriate.

My second example uses a combination of the two but unlike your suggestion of less than a second I had the Sleep period be 8 minutes.  You wrote "to keep the script "alive". Won't AdlibRegister interrupt Sleep  regardless of the Sleep period? Is there any reason to have the Sleep period be real short vs fairly long (500ms vs 8 minutes), especially when AdlibRegister will cause the interrupt in 5 minutes intervals?

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

timmy2,

We did some tests a good few years ago (someone had developed a method of pausing for very short periods) and found that you needed to pause the CPU for only about 100 nano-seconds to keep the load down - so the minimum useable value of Sleep(10) (10 milli-seconds) should be more than sufficient in your idle loop whichever method you choose.

M23

Edited by Melba23
Got timings wrong

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

I suppose not, I just figured that if you're going to use a long sleep why use Adlibregister() at all just use sleep.

Share this post


Link to post
Share on other sites

Sleep(10) is 10 milliseconds, and 100 nanoseconds sleep isn't possible in AutoIt, it can be done without using the AutoIt Sleep function, but you can't use Sleep to go less than 10 milliseconds.


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

timmy2,

We did some tests a good few years ago (someone had developed a method of pausing for very short periods) and found that you needed to pause the CPU for only about 100 nano-seconds to keep the load down - so the minimum useable value of Sleep(10) (10 milli-seconds) should be more than sufficient in your idle loop whichever method you choose.

M23

Thank you for replying, Melba23. From your reply I'm not sure what you mean by "you need to pause the CPU".  Let's put my question this way: since my goal is to check for messages every 5 minutes are there any bad side effects from using Sleep (300000), and if so is there a better solution?

Share this post


Link to post
Share on other sites

Thank you for replying, Melba23. From your reply I'm not sure what you mean by "you need to pause the CPU".  Let's put my question this way: since my goal is to check for messages every 5 minutes are there any bad side effects from using Sleep (300000), and if so is there a better solution?

No that's fine. Go ahead with that Sleep().

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

  • Similar Content

    • badcoder123
      By badcoder123
      Hey everyone,
      I've been messing around with some new things and adlibs look extremely useful/interesting, however, I can't seem to get it to work.. Here's what I have
      HotKeySet("{F1}", "_Exit") $qCount = 1 Global $_Timer AdlibRegister($_Timer, 1000) AdlibUnRegister($_Timer) While 1 SoundPlay(@WindowsDir & "\media\tada.wav", 1) $qCount += 1 ToolTip('"Tada" has been played ' & $qCount & " times",200,200) WEnd Func _Timer() Local Static $iCount += 1 ConsoleWrite($iCount) If $iCount = 20 Then ConsoleWrite("iCount is at " & $iCount) EndFunc Func _Exit() Exit EndFunc Basically I want it to call the _Timer function but it doesn't seem to work :/ any ideas?
    • Nareshm
      By Nareshm
      I have script Like This :
      Opt("TrayAutoPause",0)
      $var = Ping("www.google.com")
      If not @error Then
      WinActivate ( "testapp")
      ControlClick ( "testapp", "", "[Savetest]")
      ControlSend ( " :: Gujarat TPDS  - eFPS :: Version - 2.2.0.0  - [eFPS Bill]", "", "[NAME:btnSavebyFP]", "{enter}")
      WinWait(":: Aadhar/EID/Verification Number Entry ::")
      ControlClick(":: Aadhar/EID/Verification Number Entry ::", "", "[NAME:btnNext]")
      If WinExists ("Aadhar : Length Check") Then
         ControlClick("Aadhar : Length Check", "", "[CLASS:Button; INSTANCE:1]")
         ControlSend(":: Aadhar/EID/Verification Number Entry ::", "", "[NAME:txtAadharNumber]", "{backspace}")
         ControlSend(":: Aadhar/EID/Verification Number Entry ::", "", "[NAME:txtAadharNumber]", "^v")
         ControlClick(":: Aadhar/EID/Verification Number Entry ::", "", "[NAME:btnNext]")
         WinWait(" :: Barcoded Ration Card Members - Biometric Verification/Check Utility ::")
         ControlSend("[Class:WindowsForms10.Window.8.app.0.378734a]", "", "[NAME:PictureBox2]", "{tab} {enter}")
         Sleep(5600)
         RunWait("rasdial /disconnect", "", @SW_HIDE) ; Stop connect from start
         RunWait("rasdial Internet", "", @SW_HIDE) ; Connect again
         Exit
      EndIf
      WinWait(" :: Barcoded Ration Card Members - Biometric Verification/Check Utility ::", "", 1)
      ControlSend("[Class:WindowsForms10.Window.8.app.0.378734a]", "", "[NAME:PictureBox2]", "{tab} {enter}")
      Sleep(5600)
      RunWait("rasdial /disconnect", "", @SW_HIDE) ; Stop connect from start
      RunWait("rasdial Internet", "", @SW_HIDE) ; Connect again
      Exit
      Else
         #include <MsgBoxConstants.au3>
         MsgBox($MB_TOPMOST, "Connection Status", "Internet is not Connected")
      Exit
      Endif
    • Nareshm
      By Nareshm
      How can i add sleep command using internet speed.
      If my internet speed is 40-50Kbps then sleep for 5 seconds,
      If my internet speed is 30-40Kbps then sleep for 4 seconds,
      If my internet speed is 20-30Kbps then sleep for 3 seconds.

      *Sleep command used bitween my costom script, Example,
      RunWait("rasdial /disconnect", "", @SW_HIDE) ; Stop connect from start
      Sleep(5000)
      RunWait("rasdial Internet", "", @SW_HIDE) ; Connect again
       
    • lacamel
      By lacamel
      Hi there,
      I did a short script to simulate mouse click when pixel change is detected on a small section of the screen. I recorded the screen many times to see the accuracy of the script and it seems though response time varies widely.
      Here's the script 
      $checksum = pixelchecksum (400,250, 402,252)
      While $checksum = pixelchecksum (400,250, 402,252)
      Sleep (50)
      Wend
      Sleep (300)
      Mouseclick("left", 450,300, 1, 0)
      Counting from the pixel change to the mouse click, i get response times anywhere between 370ms and 550ms. I've tried running au3 and exe, changed sleep times but never gotten an accurate response time based on the script. Any ideas why?
    • InunoTaishou
      By InunoTaishou
      Update 2017-04-21:
      Added a timeout My previous attempt of checking that the function is valid was not working. Added a 1 time function call before entering the While loop to test the function. Now sets error to $SLEEP_UNTIL_INVALID_CALL if the function supplied is does not exist or invalid arguments supplied Added an @Error value $SLEEP_UNTIL_TIMEOUT_REACHED, set when the condition was not met but timeout reached Update 2017-04-25:
      Thanks to @jguinchfor letting me know about Execute(). Greatly simplified the loop (didn't know that Execute would execute a function call statement)
      Any strings passed to the SleepUntil() function need to be enclosed in " or ' (I.e', SleepUntil("ConsoleWrite('This is a test' & @LF)")) Adjusted SleepUntil() to use the Execute() function instead Inspired by a very vague topic, and completely unnecessary, I had fun trying to making this up. A function that will sleep until the conditional statement, or function call statement, provided executes to the condition you want! I know, completely useless!!! It's pretty interesting actually. Instead of having to write multiple while loops per conditions, you just need to use SleepUntil and set your own condition.
      Basic syntax:
      SleepUntil("$iMyNumber = 100") Will sleep until the variable in your script $iMyNumber is 100. All conditional operators are supported (=, <>, >=, <=, >, and <). Currently does not support multiple conditions (i.e., $iMyNumber > 100 and $iMyNumber < 1000).
      More advanced syntax, using a value returned from a function call:
      SleepUntil("TimerDiff(" & TimerInit() & ") > 5000") Well check the value returned from TimerDiff using the value returned from TimerInit() and stop sleeping once it's > 5000 (5 seconds).
      Anyways, better to show through the example.
      Example.au3
      #include <String.au3> #include <Array.au3> #include <GUIConstants.au3> #include <GuiEdit.au3> #include "SleepUntil.au3" AutoItSetOption("GUICloseOnESC", 0) Global $sName = "Test" Global $bBool = True Global $iInt = -1 Global $dDouble = 0.0 Global $sMsg = "Welcome," & @CRLF & _ "The SleepUntil function can use a function to check against a condition or just a regular conditional statement. " & _ "I.e. $iValue = 300" & @CRLF & "A basic conditional example would be" & @CRLF & @TAB & _ "Global $bWaiting = True" & @CRLF & @TAB & _ 'SleepUntil("$bWaiting <> $bWaiting")' & @CRLF & _ "This is a good example of having some kind of global flag where you want to wait until the user triggers the flag to not be true" & @CRLF & @CRLF & _ "The first set of examples will use function calls to compare against the condition value." & @CRLF & _ "First example calls GUIGetMsg using the with no arguments and sleeps until the value returned is " & _ "$GUI_EVENT_CLOSE" & @CRLF & @CRLF & _ "Syntax for the function call for SleepUntil is like normal:" & @CRLF & _ 'SleepUntil("FunctionName(Argument1, Argument2, ArgumnetN) (Condition Operator) Value' & @CRLF & _ 'Example (Where function call has arguments)' & @CRLF & @TAB & _ 'Global $iTimer = TimerInit()' & @CRLF & @TAB & _ 'SleepUntil("TimerDiff(" & $iTimer & ") >= 5000")' & @CRLF & @CRLF & _ "Example (Where no arguments are needed for the function)" & @CRLF & @TAB & _ 'SleepUntil("GUIGetMsg() = $GUI_EVENT_CLOSE")' & @CRLF & @CRLF & _ "The first example will start once you close this window!" Global $hMain = GUICreate("Introduction", 800, 600, 0, 0, BitOR($WS_SIZEBOX, $WS_MAXIMIZEBOX, $WS_MINIMIZEBOX)) Global $edtEdit = GUICtrlCreateEdit($sMsg, 10, 10, 775, 555, $ES_MULTILINE) GUICtrlSetBkColor($edtEdit, 0x1F1F1F) GUICtrlSetColor($edtEdit, 0xF1F1F1) GUICtrlSetFont($edtEdit, 11, 400, "", "Consolas") GUICtrlSetResizing($edtEdit, $GUI_DOCKLEFT + $GUI_DOCKRIGHT + $GUI_DOCKTOP + $GUI_DOCKBOTTOM) GUISetState(@SW_SHOWMAXIMIZED) _GUICtrlEdit_SetSel(GUICtrlGetHandle($edtEdit), 0, 0) ; Slep until person running this example script closes the GUI or it reaches the 30 second timeout SleepUntil("GUIGetMsg() = $GUI_EVENT_CLOSE", 50, 30000) GUIDelete($hMain) MsgBox("", "Timer", "Starting the examples. The next sleep will last until 2 seconds have passed") ; Sleep until TimerDif(Timer Created) > 2000 ToolTip("Sleeping until 2 seconds has passed", 0, 0) SleepUntil("TimerDiff(" & TimerInit() & ") >= 2000") MsgBox("", "Timer", "2 Seconds has passed. Met condition and left sleep function") ; Sleep until the call to ConsoleWrite3Times is >= 3 ToolTip("Sleeping until the function ConsoleWrite3Times() as been called three times", 0, 0) SleepUntil("ConsoleWrite3Times('This is a test!') >= 3", 500) MsgBox("", "Print 3 Times", "Did ConsoleWrite 3 times. Met condition needed and left sleep function") MsgBox("", "Next", "Next SleepUntil examples can be met by pressing the {F1} Key to trigger the conditions" & @CRLF & _ "Next example will sleep until $sName = InunoTaishou") HotKeySet("{F1}", SetName) ; Sleep until user presses {F1} and changes $sName = InunoTaishou ToolTip("$sName = " & $sName, 0, 0) SleepUntil("$sName = 'InunoTaishou'", 100) MsgBox("", $sName, "Name has been updated to " & $sName & ". Met condition needed and left sleep function" & @CRLF & _ "Next example will sleep until $bBool <> True") ; Sleep until user preses {F1} and $bBool <> True ToolTip("$bBool = " & $bBool, 0, 0) SleepUntil("$bBool <> " & $bBool, 100) MsgBox("", $bBool, "Bool has been updated to " & $bBool & ". Met condition needed and left sleep function" & @CRLF & _ "Next example will sleep until $iInt > 0") ; Sleep until user presses {F1} and $iInt > 0 ToolTip("$iInt = " & $iInt, 0, 0) SleepUntil("$iInt > 0", 100) MsgBox("", $iInt, "Int has been updated to " & $iInt & ". Met condition needed and left sleep function" & @CRLF & _ "Next example will sleep until $dDouble = 99.99") ; Sleep until user presses {F1} and $dDouble = 99.99 ToolTip("$dDouble = " & $dDouble, 0, 0) SleepUntil("$dDouble = 99.99", 100) MsgBox("", $dDouble, "Double has been updated to " & $dDouble & ". Met condition needed and left sleep function" & @CRLF & _ "Next example will sleep until function Print is called with the msg provided") Local $sMsgToPrint = InputBox("Message", "What message should be used for ConsoleWrite?", "This is a the default msg!") SleepUntil("Print('" & $sMsgToPrint & "', " & InputBox("Times?", "How many times to print " & $sMsgToPrint & "?", 10) & ") = '" & $sMsgToPrint & "'") MsgBox("", "Print", "Congrats! That's all the examples I have") Func ConsoleWrite3Times($sMsg) Local Static $iPrint = 0 $iPrint += 1 ConsoleWrite("[" & $iPrint & "] " & $sMsg & @LF) Return $iPrint EndFunc Func Print($sMsg, $iTimes) If ($iTimes < 1) Then $iTimes = 1 For $i = 1 to $iTimes ConsoleWrite($sMsg & @LF) Next Return $sMsg EndFunc Func SetName() $sName = "InunoTaishou" HotKeySet("{F1}", SetBool) EndFunc ;==>SetName Func SetBool() $bBool = False HotKeySet("{F1}", SetInt) EndFunc ;==>SetBool Func SetInt() $iInt = 100 HotKeySet("{F1}", SetDouble) EndFunc ;==>SetInt Func SetDouble() $dDouble = 99.99 EndFunc ;==>SetDouble SleepUnti.au3
      #include-once #include <String.au3> Global Const $SLEEP_UNTIL_INVALID_EXECUTE = -100 Global Const $SLEEP_UNTIL_TIMEOUT_REACHED = -101 ; #AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w- 4 -w 5 -w 6 -w- 7 ; #CURRENT# ===================================================================================================================== ; SleepUntil: Sleeps until the condition statement supplied meets the requirements ; =============================================================================================================================== ; #FUNCTION# ==================================================================================================================== ; Name ..........: SleepUntil ; Description ...: Sleeps until the condition supplied is met. ; Syntax ........: SleepUntil($sConditionStatement[, $iTime = 100[, $iTimeout = Default]]) ; Parameters ....: $sConditionStatement - String formatted condition statement ; $iTime - (Optional) Time (In Milliseconds) to sleep between each check of the condition ; $iTimeout - (Optional) Timeout (In Milliseconds) to stop sleeping if condition not met ; Return values .: Success - Returns True when the condition is met ; Failure - Returns False and Sets the @Error flag ; -100 ($SLEEP_UNTIL_INVALID_EXECUTE): Function supplied does not exist or parameters supplied do not match ; the function called ; -101 ($SLEEP_UNTIL_TIMEOUT_REACHED): Timeout was reached but the condition was not met ; Author ........: InunoTaishou, jguinch for letting me know about Execute() ; Thanks jguinch! Greatly simplified the script ; Remarks .......: The $sConditionStatement parameter can be a simple $vVar = Value or can use the value returned from a function call ; to sleep. ; Proper syntax for a function call is a normal AutoIt function call: "MsgBox(0, 'Title', 'Message')" ; Example .......: Yes ; =============================================================================================================================== Func SleepUntil($sConditionStatement, $iTime = 100, $iTimeout = Default) Local $iTimer = ($iTimeout ? TimerInit() : Null) While (Not Execute($sConditionStatement)) If (@Error) Then Return SetError($SLEEP_UNTIL_INVALID_EXECUTE, 0, False) If ($iTimeout and TimerDiff($iTimer) >= $iTimeout) Then Return SetError($SLEEP_UNTIL_TIMEOUT_REACHED, 0, False) Sleep($iTime) WEnd Return True EndFunc ;==>SleepUntil Edit: Did a test call to the function to make sure it's valid. checking for the 0xDEAD and 0xBEEF errors inside the while loops wasn't working since the _EvalCondition was being called right after it.
      Edit: Forgot about the _ that can be used in function calls. Added the _ to the StringRegExp