Jump to content
Sign in to follow this  
Amaruq

Delayed function

Recommended Posts

Amaruq

Hello all,

I'm using a script that consist of several functions, so far so good.

Now I have received a request to delay the execution of one function by 5 minutes, once it is called, without delaying the rest of the script. If the same function should be called again within these 5 minutes it should 'ignore' this most recent call and continue with the previous one.

The function uses an array as parameter and gets called upon when the modified date of a file changes.

Can anyone point me in the right direction on how to properly handle this please?

Thanks in advance.

Share this post


Link to post
Share on other sites
SadBunny

Something like this perhaps?

HotKeySet("x", "doSomethingSpecialTrigger")

; we will wait for 5000 milliseconds after the hotkey is pressed
Global $timeOutInMs = 5000
Global $specialTimer = 0

Global $loopTimer = TimerInit()

$count = 0

While 1
Sleep(10)
If (TimerDiff($loopTimer) > 1000) Then
$count += 1
ConsoleWrite("Script has been running for " & $count & " seconds." & @CRLF)
$loopTimer = TimerInit()
EndIf

If ($specialTimer <> 0) Then
If TimerDiff($specialTimer) > $timeOutInMs Then
doSomethingSpecial()
$specialTimer = 0
EndIf
EndIf
WEnd

Func doSomethingSpecial()
ConsoleWrite("*** HUGS AND KISSES TO YOU *** because you hit 'x' five seconds ago! I love x..." & @CRLF)
EndFunc

Func doSomethingSpecialTrigger()
If $specialTimer == 0 Then
$specialTimer = TimerInit()
EndIf
EndFunc
Edited by SadBunny

Roses are FF0000, violets are 0000FF... All my base are belong to you.

Share this post


Link to post
Share on other sites
stormbreaker

Just another proof of concept (10 seconds):

Global $hTimer

HotKeySet('1', '_MyFunction')

Func _MyFunction()
If NOT $hTimer then $hTimer = TimerInit()
$TIMER = TimerDiff($hTimer)
If $TIMER > 10*1000 then 
msgbox(64, '', '10 seconds exceeded.')
EndIf
EndFunc

While 1
Sleep(100)
WEnd

I assume u have some basic knowledge of functions.


----------------------------------------

:bye: Hey there, was I helpful?

----------------------------------------

My Current OS: Win8 PRO (64-bit); Current AutoIt Version: v3.3.8.1

Share this post


Link to post
Share on other sites
BrewManNH

Another idea, using MKISH's script used as a base and using the Static function.

HotKeySet('1', '_Exit')
Global $Stop = 0 ; only needed for the exit function


Func _MyFunction()
     Local Static $hTimer = TimerInit()
     $Time = 10
     If TimerDiff($hTimer) > $Time * 1000 Then
          MsgBox(64, '', '10 seconds exceeded.')
          $hTimer = TimerInit()
     EndIf
EndFunc   ;==>_MyFunction

While 1
     _MyFunction()
     Sleep(1000)
     If $Stop Then ExitLoop
WEnd
Func _Exit()
     $Stop = 1
EndFunc   ;==>_Exit

Press 1 to exit the script.

Edited by BrewManNH

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
KaFu

Here's my version :)

Global $b_Delayed_Func_Running = False, $a_Delayed_Func_Array

Func _Call_Delayed_Function($array)
    If $b_Delayed_Func_Running Then Return
    $b_Delayed_Func_Running = True
    $a_Delayed_Func_Array = $array
    AdlibRegister("_Delayed_Function", 5 * 60 * 1000)
EndFunc   ;==>_Call_Delayed_Function

Func _Delayed_Function()
    ; do something with $a_Delayed_Func_Array
    AdlibUnRegister("_Delayed_Function")
    $b_Delayed_Func_Running = False
EndFunc   ;==>_Delayed_Function

Are you delaying the function call because the file is locked? better test for a lock after filetime has changed, and proceed when lock is lifted instead of just guessing that 5 minutes will be enough.

Share this post


Link to post
Share on other sites
guinness

Another idea, using MKISH's script used as a base and using the Static function.

HotKeySet('1', '_Exit')
Global $Stop = 0 ; only needed for the exit function


Func _MyFunction()
     Local Static $hTimer = TimerInit()
     $Time = 10
     If TimerDiff($hTimer) > $Time * 1000 Then
          MsgBox(64, '', '10 seconds exceeded.')
          $hTimer = TimerInit()
     EndIf
EndFunc   ;==>_MyFunction

While 1
     _MyFunction()
     Sleep(1000)
     If $Stop Then ExitLoop
WEnd
Func _Exit()
     $Stop = 1
EndFunc   ;==>_Exit

Press 1 to exit the script.

Nice to see Static variables being used. The Global variable can be destroyed as I would have used Exit in the _Exit 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

Share this post


Link to post
Share on other sites
Amaruq

First of all my thanks to all who contributed!

By the looks of it I was searching in a too difficult direction.

I've tested with all supplied scripts and it looks like only SadBunny's versions does everything that I need.

So I'll be going with that one.

Once again, thanks to all who took the time to have a go at this!

Share this post


Link to post
Share on other sites
SadBunny

First of all my thanks to all who contributed!

By the looks of it I was searching in a too difficult direction.

I've tested with all supplied scripts and it looks like only SadBunny's versions does everything that I need.

So I'll be going with that one.

Once again, thanks to all who took the time to have a go at this!

It was the hugs&kisses, wasn't it? :) Anyway, good luck and I'm happy I was able to help.


Roses are FF0000, violets are 0000FF... All my base are belong to you.

Share this post


Link to post
Share on other sites
kylomas

Amaruk,

As far as I can tell only Kafu's script meets this requirement

without delaying the rest of the script.

And just for grins, a gui version using Kafu's technique.

; *** Start added by AutoIt3Wrapper ***
#include <WindowsConstants.au3>
; *** End added by AutoIt3Wrapper ***
; *** Start added by AutoIt3Wrapper ***
#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
; *** End added by AutoIt3Wrapper ***

#include <date.au3>

#AutoIt3Wrapper_Add_Constants=n

local $delay_time = 10, $sec = @sec, $func_timer

local $gui010 = guicreate('Main Gui',300,500)
local $edt010 = guictrlcreateedit('',0,0,300,450,bitor($es_readonly,$ws_vscroll))
guictrlsetfont(-1,8,800,-1,'Lucinda Console')
local $btn010 = guictrlcreatebutton('Start Delayed Function',10,470,270,20)
guisetstate()

while 1
switch guigetmsg()
case $gui_event_close
Exit
case $btn010
if guictrlread($btn010) = 'Start Delayed Function' Then
guictrlsetdata($btn010,'Stop Delayed Function')
guictrlsetdata($edt010,_nowtime() & ' Begin Wait for Delayed Function' & @crlf,1)
adlibregister('_delayed_function',1000)
$func_timer = timerinit()
Else
guictrlsetdata($btn010,'Start Delayed Function')
adlibunregister('_delayed_function')
EndIf
EndSwitch

if $sec <> @sec then
if mod( @sec, 3) = 0 then _issue_goofy_message()
$sec = @SEC
endif

WEnd

func _delayed_function()

ConsoleWrite(_nowtime() & ' ' & (timerdiff($func_timer)/1000) & @LF)

if (timerdiff($func_timer)/1000) >= $delay_time then
guictrlsetdata($edt010,_nowtime() & ' Delayed Function Running' & @crlf,1)
adlibunregister('_delayed_function')
guictrlsetdata($btn010,'Start Delayed Function')
$func_timer = 0
endif

if mod( int(timerdiff($func_timer)/1000), 5) = 0 then
guictrlsetdata($edt010,_nowtime() & ' Delayed Function Still waiting' & @crlf,1)
return
EndIf

endfunc

func _issue_goofy_message()

guictrlsetdata($edt010,_nowtime() & ' Main Func is running' & @crlf,1)

endfunc

Good Luck,

kylomas

edit: wrong name

edit2: My earlier stmt is full of shit, apologies...

Edited by kylomas

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
BrewManNH

How does my entry delay the script, other than the 1 second pause which is only there for demonstration purposes?


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
kylomas

BrewmanNH,

How does my entry delay the script, other than the 1 second pause which is only there for demonstration purposes?

Does it not stay in "myfunction"for 10 seconds? Perhaps I am misreading the script.

kylomas

edit: Your right! apologies...

Edited by kylomas

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
Amaruq

Hello BrewManNH,

How does my entry delay the script, other than the 1 second pause which is only there for demonstration purposes?

It doesn't. I wrote that SadBunny's version does everything I need and that is because he did another, for me, more correct interpretation of what I needed.

More specifically about how the function is being called without the need to loop _MyFunction.

Share this post


Link to post
Share on other sites
Amaruq

It was the hugs&kisses, wasn't it? :) Anyway, good luck and I'm happy I was able to help.

Well, it helped :lol:. Thanks again!

Share this post


Link to post
Share on other sites
KaFu
Amaruq

Hello KaFu,

Well, my example does neither require looping.

You are right it doesn't. But the help file states that an adlid function needs to be kept 'simple'.

I'm not an experienced scripter and it's been awhile since I had the need to use AutoIT so as I can't tell what 'simple' is for AutoIT.

The triggered function has several things to do, including connecting to and altering databases, so I choose the safe way.

Anyway, I hope this helps clear things up.

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
Sign in to follow this  

×