Jump to content

Curing excessive looping/queueing inside of while statement


 Share

Recommended Posts

How can I have a function that is inside of my while statement only run every 2 seconds, before looping and trying to run again? All the while still allowing the other functions inside of my while statement the ability to run?

I experimented with the code below, but it did not work when I incorporated functions.

$cycle = @SEC
ConsoleWrite($cycle)

While 1
;~ ConsoleWrite("Time is " & @HOUR & @MIN & @MSEC & @SEC)


If @sec = ($cycle + 2) Then ;OR @sec < 1  Then
ConsoleWrite("Looping" & @CRLF)
$cycle = @SEC
ConsoleWrite($cycle & " in if statement" & @CRLF)
ElseIf @sec = 00 Then
    $cycle = -1
    ConsoleWrite("Resetting $cycle value" & "@sec = " &@sec & @CRLF)
EndIf

Sleep(100)
WEnd

More detailed explanation

I have a script that checks registry settings and services over the network and updates and input box with the registry setting values or services conditions. For whatever reason it is looping the function again before it gets information back from the previous time the function runs, so it queues up a hundreds of calls to a server over the network (trying to populate the input box) and causes a 1 to 2 minute wait queue to do anything else in the while statement. I'd like for it to poll the service status (running/stopped and enabled/disabled) every 2 seconds and wait for the value to return, while allowing me to stop the service through a button in my gui

Here is the function to check the service status, that I am using

;===============================================================================
;
; Description:      Checks to see if a service is running
; Syntax:           _ServiceRunning($sServiceName)
; Parameter(s):     $sServiceName - Name of service to check
; Requirement(s):   None
; Return Value(s):  On Success - Returns 1
;                   On Failure - Returns 0
; Author(s):        SumTingWong
; Documented by:    noone
;
;===============================================================================
Func _ServiceRunning($sServiceName)
  Local $arRet
  Local $hSC
  Local $hService  
  Local $bRunning = 0

        If GUICtrlRead($updatelibrarylistserverinputvalue_input) <> "" AND StringLen(GUICtrlRead($updatelibrarylistserverinputvalue_input)) = 7 Then
                Local $server = GUICtrlRead($updatelibrarylistserverinputvalue_input)
                ConsoleWrite("Service name server value is " & $server & @CRLF)
;~ ;
        ElseIf GUICtrlRead($updatelibrarylistserverinputvalue_input) <> "" Then 
                local $server = @ComputerName

        EndIf
;~  EndIf
        

  $arRet = DllCall("advapi32.dll", "long", "OpenSCManager", _
                   "str", $server, _
                   "str", "ServicesActive", _
                   "long", $SC_MANAGER_CONNECT)
  If $arRet[0] <> 0 Then
     $hSC = $arRet[0]
     $arRet = DllCall("advapi32.dll", "long", "OpenService", _
                     "long", $hSC, _
                     "str", $sServiceName, _
                     "long", $SERVICE_INTERROGATE)
     If $arRet[0] <> 0 Then
        $hService = $arRet[0]
        $arRet = DllCall("advapi32.dll", "int", "ControlService", _
                         "long", $hService, _
                         "long", $SERVICE_CONTROL_INTERROGATE, _
                         "str", "")
        $bRunning = $arRet[0]
        DllCall("advapi32.dll", "int", "CloseServiceHandle", "long", $hService)
     EndIf
     DllCall("advapi32.dll", "int", "CloseServiceHandle", "long", $hSC)
  EndIf
  Return $bRunning

EndFunc
Link to comment
Share on other sites

  • Moderators

gte,

Why not call the checking function every 2 secs using AdlibRegister? Then your normal loop can run quite happily without the need for timers. :(

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see 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

 

Link to comment
Share on other sites

Hi Melba,

I have adlibenable, but not adlibregister.

I believe i have version ait 3.3.0.0, do I need to upgrade, or just install a udf?

Thanks for the reply!

-gte

gte,

Why not call the checking function every 2 secs using AdlibRegister? Then your normal loop can run quite happily without the need for timers. :(

M23

Link to comment
Share on other sites

You're running an obsolete version. Upgrade both Scite4AutoIt3 and AutoIt, then be sure to read the changelog in full. You may have to change some things but it will definitely be much better.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Ok, I updated and used adlibregister, thanks!

I have a switch/case statement in my while statement.

It appears that after I press a button triggering something in my case statement, it keeps looping on that individual case statement option endlessly? I even tried setting $nMsg = "" at the end???

Any idea what would cause that?

While 1
$nMsg = GUIGetMsg()
Switch $nMsg
;~  ConsoleWrite("$nMsg is " & @CRLF)
    Case $GUI_EVENT_CLOSE
        Exit

    Case $countfiles_button

            FileDelete("c:\temp\testxmls\*.xml")
            $sPath = "D:\dma\fecs\downloadbak"
            $zipfilelist = _FileListToArray($sPath,"*.zip",1)
            If fileread("c:\temp\testxmls\*.xml") = 1 Then
                            $deletexmls_button = MsgBox(3, "XML files are already in directory", "Delete existing files in c:\temp\testxmls ?")
                            if $deletexmls_button = 6 Then
                                FileDelete("c:\temp\testxmls\*.xml")
                            ElseIf  @Error=1 Then
                            EndIf
                        MsgBox (0,"","No Files\Folders Found.")
                        Exit
            EndIf



                    _unziposindependent()
                    if $didnotfindzipfiles = 1 then
                        ContinueCase
                    EndIf
                    MsgBox(0, "XML Transaction Counting", "Completed! And completed 727% faster than the old program!")
;~
                    $sString = "</Document>"
                    $aFileList = _FileListToArray("c:\temp\testxmls", "*.xml", 1)               ; Lists .xml files and\or folders in c:\temp\testxmls

                    FileDelete("c:\temp\testxmls\results.txt")                                  ; deletes old result findings


                    For $i = 1 To $aFileList[0] Step 1                                              ; variable $i = from line 1 to the end of the array

                            $iCount = UBound (StringRegExp(FileRead("c:\temp\testxmls\" & $aFileList[$i]), "(?i)(" & $sString & ")", 3))  ; variable iCount equals the query of the file read c:\temp\testxmls\filearrary, string to search for without case sensitivity, search globally

                        FileWrite("c:\temp\testxmls\results.txt", $iCount & @CRLF)              ; puts the results of each file, one line at a time
                        ConsoleWrite($i & " - " & $iCount & @CRLF) ; writes the console below

                    Next

                    $fileread = FileRead("c:\temp\testxmls\results.txt")                        ; reads the results file output

                    $out = StringReplace($fileread, @CRLF, "+")                                 ; replaces a carriage return with a plus symbol
                    If StringRight($out,1) = "+" Then                                           ; trims the last plus symbol from the equation if it's there
                        $out = StringLeft($out,StringInStr($out,"+",0,-1)-1)                    ; variable out = evalulte $out string, get the count by taking the string $out, substring of +, not case sensitive, from the right side
                    EndIf

                    $sum = Execute($out)

                    $cleanup = RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\DMA\FECS\applications\Cleanup", "Delay - Processed")                ; read the registry key value
;~                  ; MsgBox(0, 2, $cleanup)

                    $average = Round(($sum / $cleanup),3)                                       ; do the math of total divided by days cleanup saves for, and round it to the 3rd decimal
                    GUICtrlSetData($daysfilesretained_input, $cleanup & " is the number of days files are retained for")
                    GUICtrlSetData($totalfilesfound_input, $sum & " transactions found")
                    GUICtrlSetData($averagetransperday_input, $average & " per day")
                    GUICtrlSetData($daysneededfor500_input, Round((500/$average),2) & " days for 500 transactions")
                    GUICtrlSetData($daysneededfor1000_input, Round((1000/$average),2) & " days for 1000 transactions")

    Case    $stopdisableunzipFHD_button
            _stopdisableunzip()

    Case    $stopdisablenotificationFRD_button
            _stopdisablenotification()

    Case    $startenablenotificationFRD_button
            _startenablenotification()

    Case    $startenableunzipFRD_button
            _startenableunzip()

    Case    $createholdfoldersFRD_button
            _createholdfolders()

    Case    $checkcurrentsettingsLL_button
            _checklibrarylist()
            _adlibfunctions()

    Case    $applystopdisableLL_button
            _updatelibrarylist()
            _stopdisablenotification()

    Case    $startenablenotificationLL_button
            _startenablenotification()

    Case    $counttransactions_button
            _countfilesinnotification()
            GUICtrlSetData($counttransactionsnotification_input, $notificationcountsum)

            _countfilesinnotification_datestresstest()
            GUICtrlSetData($counttransactionsdatestresstest_input, $notificationStressTestcountsum)

            _countfilesinnotification_datebackup()
            GUICtrlSetData($counttransactionsbackup_input, $notificationBackupcountsum)

    Case    $appyupdate_button
            _updatelibrarylist()

    Case    $restartnotificationLL_button
            _restartnotification()

    Case    $scanstationchangevaluechange_button
            _changescanstationserver()

    Case    $scanstationchangevaluescheck_button
            _checkscanstationserver()


EndSwitch


AdlibRegister("_adlibfunctions", 1000)


Sleep(100)      ; This is to stop flutter with the GUI

$nMsg = ""

WEnd
Link to comment
Share on other sites

  • Moderators

gte,

You need only declare the Adlib function once, so please move it out of the loop. :(

Any idea what would cause that?

Not without seeing more of the code. Does it happen for any control or just some?

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see 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

 

Link to comment
Share on other sites

Ok, I moved it out, apps is giving this error, not quite sure how to fix it yet

!>10:38:33 AutoIT3.exe ended.rc:-1073741502

When the app was running, it would only happen for a particular control after I triggered it via a button click

gte,

You need only declare the Adlib function once, so please move it out of the loop. :(

Not without seeing more of the code. Does it happen for any control or just some?

M23

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...