Jump to content

How to pause timers in autoit


Recommended Posts

Im using the timers in autoit eg

 _Timer_SetTimer($hGUI, $aTimerVal[0][$Interval][0] * 1000, _CB_Step)

and using a parametric callback so all the instances are referencing the same callback. Is there a simple way of globally pausing the script? I want the user to simply press a pause/continue button to control the script.

Please dont reply with sleep() unless there is something I dont understand...Sleep does not seem to affect the timers at all...only interaction etc

Even when going the au3 > exe route; the pause script in tray does not work.

Maybe a _PauseAllTimers function in the Timers.a3 udf...dont have a clue how to implement though?

Many thanks

Mark

Edited by Architerion
Link to comment
Share on other sites

HotKeySet("{PAUSE}", "TogglePause")

Func TogglePause()
    $Paused = NOT $Paused
    While $Paused
        sleep(100)
        ToolTip('Script is "Paused"',0,0)
    WEnd
    ToolTip("")
EndFunc

Used to use this alot in the past. Works well.

Get Scite to add a popup when you use a 3rd party UDF -> http://www.autoitscript.com/autoit3/scite/docs/SciTE4AutoIt3/user-calltip-manager.html

Link to comment
Share on other sites

Im using the timers in autoit eg

 _Timer_SetTimer($hGUI, $aTimerVal[0][$Interval][0] * 1000, _CB_Step)

and using a parametric callback so all the instances are referencing the same callback. Is there a simple way of globally pausing the script? I want the user to simply press a pause/continue button to control the script.

Please dont reply with sleep() unless there is something I dont understand...Sleep does not seem to affect the timers at all...only interaction etc

Even when going the au3 > exe route; the pause script in tray does not work.

Maybe a _PauseAllTimers function in the Timers.a3 udf...dont have a clue how to implement though?

Many thanks

Mark

_Timer_KillAllTimers() will provide a clue as to how you can create your own wrapper function.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

HotKeySet("{PAUSE}", "TogglePause")

Func TogglePause()
    $Paused = NOT $Paused
    While $Paused
        sleep(100)
        ToolTip('Script is "Paused"',0,0)
    WEnd
    ToolTip("")
EndFunc

Used to use this alot in the past. Works well.

 

See the example code in the Help file for the HotKeySet function. Maybe that'll work for you.

 

Thanks for the replies...unfortunately, as mentioned, sleep has no effect.

Guiness...can you divulge further? I checked it out but user32.dll does not seem to have any 

BTW...Why does sleep not pause the timers? Would be good if there was an opt for it?

Link to comment
Share on other sites

What about something like this?

Timer("TimerInit")
Sleep(1000)
ConsoleWrite(Timer("TimerDiff") &@CRLF)
Timer("Pause")
Sleep(1000)
Timer("Resume")
Sleep(1000)
ConsoleWrite(Timer("TimerDiff") &@CRLF)


Func Timer($Query)
    Static $Timer, $Pause
    Switch $Query
        Case "TimerInit"
            $Timer = TimerInit()
            $Pause = 0
        Case "TimerDiff"
            Return TimerDiff($Timer) + $Pause
        Case "Pause"
            $Pause = Pause + TimerDiff($Timer)
        Case "Resume"
            $Timer = TimerInit()
    EndSwitch
EndFunc
Edited by Geir1983
Link to comment
Share on other sites

See the example code in the Help file for the HotKeySet function. Maybe that'll work for you.

 

Thanks for the replies...unfortunately, as mentioned, sleep has no effect.

Have you tried that code? The Sleep function in that code is a short time (100 milliseconds) in the While loop to ease up CPU usage, and it's the While loop and the definition of the $Pause variable are what actually 'pause' the script. I'm just trying to point out that the Sleep function isn't used to 'pause'. Well it is, but it isn't.. B) I haven't used any of the Timer UDF's so maybe they do 'run in the background' and that code will have no effect on your script. Edited by somdcomputerguy

- Bruce /*somdcomputerguy */  If you change the way you look at things, the things you look at change.

Link to comment
Share on other sites

The timers used are the computer's timers, not AutoIt's that's why sleep has no affect. Sleep only affects the operation of AutoIt code, when you read the timers you're reading from values set in your motherboard's timers.

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

Link to comment
Share on other sites

The timers used are the computer's timers .. when you read the timers you're reading from values set in your motherboard's timers.

I can see from this code (taken from Help file example codes), and also from your explanation BrewManNH, just what's going on. Thanks. B) Sorry to have wasted your time, Architerion.

#include <Timers.au3>

Global $Paused
HotKeySet("{PAUSE}", "TogglePause")
HotKeySet("{ESC}", "_Quit")

Local $starttime = _Timer_Init()
While 1
    ToolTip(_Timer_Diff($starttime) / 1000)
WEnd

Func TogglePause()
    $Paused = Not $Paused
    While $Paused
        Sleep(100)
        ToolTip('Script is "Paused"', 0, 0)
    WEnd
    ToolTip("")
EndFunc   ;==>TogglePause

Func _Quit()
    Exit
EndFunc   ;==>_Quit

- Bruce /*somdcomputerguy */  If you change the way you look at things, the things you look at change.

Link to comment
Share on other sites

 _Timer_SetTimer($hGUI, $aTimerVal[0][$Interval][0] * 1000, _CB_Step)

How about:

HotKeySet("{Pause}", "TogglePause")

Global $Timer = TimerInit()
Global$jTimer = 0
$hGUI = "notepad"
While 1
_Timer_SetTime($hGUI, ($aTimerVal[0]-$jTimer)[$interval][0] * 1000._CB_Step)
WEnd

Func TogglePause($kTimer);returns value of $jTimer which is th difference from when the script was paused and the time it was started again
Local $hTimer = TimerDiff($Timer);Time difference since beginning of script
Local $mTimer = $kTimer
    Sleep(500);Wait for user to stop pressing pause
     Local $iTimer = TimerDiff($Timer);get time difference from when the pause key is pressed)
     Local $kTimer = $iTimer - $hTimer
     If $kTimer >= 0 Then
          $kTimer = $kTimer + $mTimer;If the script is paused more than once then add up the total time paused so the script can get the difference which will make the script appear to pause the global timer 
     Return $kTimer;Difference between when timer was paused and when the timer was started again
     If _isPressed("{PAUSE}") Then;if the user presses pause again then get time difference
          $tTime = TimerDiff($Timer)
     Else Sleep(10)
EndFunc

Haven't tried the code. Just put it together. Basically what it is designed to do is get a time stamp at the start of the script and if the script is paused it will record the time it has been paused and subtract the time paused from the time stamp of the main program. If its paused more than once then it will add the values of the old paused time and the new paused time. Its late and I haev to crash but there still needs to be a while loop added based upon how you let your users know that the script is paused. I dont know about the interval value in _Timer_SetTime but I think the interval would need to have less time remaining than the amount of time the pause lasts.

Get Scite to add a popup when you use a 3rd party UDF -> http://www.autoitscript.com/autoit3/scite/docs/SciTE4AutoIt3/user-calltip-manager.html

Link to comment
Share on other sites

Thanks so much everyone for your efforts.
 
Here is a bit more code to help make sense of it all. Im simply making an 8 channel timer (using the FTD udf) for a usb controlled relay. Each 'channel' of the relay can be a one shot timer or it may have a number of on/off segments depending on the steps defined in the array. It uses a parametised single callback to handle turning a relay on/off or terminate if sequence has finished.

As mentioned sleep, positively absolutely has no effect no matter how long the pause etc
 
 

;~ -------- Ch3 
; [x][n][n] = channel/timer number
; [n][x][n] = sequence step number
; [n][n][0] = actual interval, [n][n][1] = relay state on/off ie 0 or 1
;

;example sequence, this step will delay start by 10 secs
$aTimerVal[2][0][0] = 10
$aTimerVal[2][0][1] = 0

;relay on for 14.5
$aTimerVal[2][1][0] = 14.5
$aTimerVal[2][1][1] = 1

;finish this timer
$aTimerVal[2][2][0] = -1
$aTimerVal[2][2][1] = 0


;CB Step = callback step through sequence
 
$aTimer[0][0] = _Timer_SetTimer($hGUI, $aTimerVal[0][$Interval][0] * 1000, _CB_Step)

;~ Callback for timer
Func _CB_Step($hWnd, $Msg, $iIDTimer, $dwTime)
   #forceref $hWnd, $Msg, $iIDTimer, $dwTime
;~ Internal timer id offset by 1000
   $CurrTimer = $iIDTimer - 1001
;~    increment the step counter of the current called Timer
   $aTimer[$CurrTimer][$StepCount] += 1
;~ use the step counter to locate the current interval in the array   
   $CurrInterval = $aTimerVal[$CurrTimer][ $aTimer[$CurrTimer][$StepCount]][0]
;~    RSOnOff = relay state on/off, store as element in array
   $RSOnOff =  $aTimerVal[$CurrTimer][ $aTimer[$CurrTimer][$StepCount]][1]
   ConsoleWrite(@CR & $RSOnOff)
;~    flag of -1 used to end current timer
  If $CurrInterval = -1 Then
      ConsoleWrite(@CR & "Curr Timer(" & $CurrTimer & ") Has Completed")
      SetRelays($Rel[$CurrTimer], 0)
      _Timer_KillTimer($hWnd, $iIDTimer)
  Else
      $iIDTimer = _Timer_SetTimer($hGUI, Abs($CurrInterval) * 1000, "", $iIDTimer)
      SetRelays($Rel[$CurrTimer], $RSOnOff)
      ConsoleWrite(@CR & "Curr Timer(" & $CurrTimer & ") Step : " & $aTimer[$CurrTimer][1] & " | Interval = " & $CurrInterval & " Rel State | " & $RSOnOff )
  EndIf
 EndFunc

Hope that makes sense...its not all the code but should create a schematic. I simply want to pause the script

Edited by Architerion
Link to comment
Share on other sites

Does any part of your code use TimerInit and TimerDiff?

 

No, because it doesnt have a callback function...so you have to poll the events which is very cpu hungry in comparison to a _sink. I guess I could recode it but I would rather it clean...unless Im missing something. Managing 8 separate timers will get pretty verbose especially with each one having different sequencing as described.

Link to comment
Share on other sites

There is no way to do this in autoit without using timerinit and timerdiff. You would need to stop your motherboards internal lock which is not possible. You could just end the program and start it again. You could maybe set a hotkey that would record the time left on each channel and save the data to a file and when you opened the program again it could check if the file had data in it and load the values from it so you would basically carry on. Unless you ran 2 scripts (1 for listening for the hotkey so you could restart your program and 1 as your main script) I don't think you could give the appearance of pause and resume.

Edited by computergroove

Get Scite to add a popup when you use a 3rd party UDF -> http://www.autoitscript.com/autoit3/scite/docs/SciTE4AutoIt3/user-calltip-manager.html

Link to comment
Share on other sites

Have you checked my Stopwatch UDF? This offers a way to pause a timer.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

Have you checked my Stopwatch UDF? This offers a way to pause a timer.

Thanks but as mentioned...it uses TimerInit/diff and running this in 8 channels with required features is of course possible but not practical. Im not saying that I would want to stop the system timer...that is of course also given as being not possible, I was looking for a udf function that might somehow handle that.

Nice work though!

Link to comment
Share on other sites

just an idea. don't know if this can have a sense in your case, but couldn't you insert a check at the beginning of the _CB_Step() function so that if a Global variable (say $paused) is set to true then you just return, else you go straight normally? something like this:

;~ Callback for timer
Func _CB_Step($hWnd, $Msg, $iIDTimer, $dwTime)
   #forceref $hWnd, $Msg, $iIDTimer, $dwTime
   If $paused then Return
   ;

 

image.jpeg.9f1a974c98e9f77d824b358729b089b0.jpeg Chimp

small minds discuss people average minds discuss events great minds discuss ideas.... and use AutoIt....

Link to comment
Share on other sites

My UDF uses the native functions only as a last option.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

 

just an idea. don't know if this can have a sense in your case, but couldn't you insert a check at the beginning of the _CB_Step() function so that if a Global variable (say $paused) is set to true then you just return, else you go straight normally? something like this:

;~ Callback for timer
Func _CB_Step($hWnd, $Msg, $iIDTimer, $dwTime)
   #forceref $hWnd, $Msg, $iIDTimer, $dwTime
   If $paused then Return
   ;

Hmmm...but there might be 2 minutes between callbacks on various timers! As well as the timer is still running for that interval.

Edited by Architerion
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...