Sign in to follow this  
Followers 0
alexlimlexart

two functions run simultaneously

16 posts in this topic

Is it possible to run or call two separate functions simultaneously? If it is then any sample? THANKS.

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

You can run two scripts simultaneously without any problem. I suspect that running two functions in the same script at the same time may be possible. What is more usual however is to interrupt a process using a second function, I think this counts. The answer to your question will most likely depend on what these functions are doing. Can you justify doing this. - realize that functions can be called from within other functions, so why would you want to call two functions at the same time?

Edited by czardas

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

Have your checked out adlibregister() in the help file?

Very little truly is processed simultaneously, and from what Ive read autoit doesn't really do multi-threading. You could try running separate processes and have them talk to each other via a named pipe

Edited by DicatoroftheUSA

Share this post


Link to post
Share on other sites

There is going to be some lag, but take a look at the functions you can create a separate .au3 file and then using your compiled script use the commandline /AutoIt3ExecuteScript to create a new process of that AutoIt code. I've sometimes done this when I've needed to download a new file but didn't want to halt the entire script just for that (and yes I do know about the background option in InetGet before someone asks.)


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_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: 04/09/2015

Share this post


Link to post
Share on other sites

#5 ·  Posted (edited)

thanks for the quick replies. I have functions.. one that loads a list of file details (SQLite3), and the rest would be the regular functions for the interface. Now loading takes time since it has to read and load 1000 files or more... and everything halts until loading is finish. This is a serious lag.

Edited by alexlimlexart

Share this post


Link to post
Share on other sites

Other than running 2 scripts at the same time, there's no way to have 2 functions run at the same time. AdLibs don't run at the same time as other functions, they halt the running function, and run the new one, and then when that's done goes back to the original one if I understand it correctly.


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

alexlimlexart,

One way would be to run a separate script, as guinness suggested.

I put together a simple sample using a ListView to show how easily it can be done.

Main.au3

#include <GUIConstantsEx.au3>

$Form1 = GUICreate("Demo1", 640, 480)
$ListView1 = GUICtrlCreateListView("", 5, 5, 630, 470)

; Call external script to populate ListView while application continues to load normally
$PID = Run(@AutoItExe & ' /AutoIt3ExecuteScript "' & @ScriptDir & 'DemoLoadValues.au3' & '"')

GUISetState(@SW_SHOW)

While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit
    EndSwitch
WEnd

DemoLoadValues.au3

#include <GUIConstantsEx.au3>
#include <GuiListView.au3>

; Get a handle to the ListView from your calling script
$ListView1 = ControlGetHandle("Demo1", "", "[CLASS:SysListView32; INSTANCE:1]")

; Here is a simple populate simulation as a proof of concept.
; Your data source would be SQLite, I just used some literals for simplicity.
_GUICtrlListView_InsertColumn($ListView1, 0, "Product ID", 150)
_GUICtrlListView_InsertColumn($ListView1, 1, "Product Name", 200)
For $i = 0 To 2000
    _GUICtrlListView_AddItem($ListView1, "IJ" & $i + 1000)
    _GUICtrlListView_AddSubItem($ListView1, $i, "Product" & $i, 1)
Next

Hope this helps :)

Share this post


Link to post
Share on other sites

#8 ·  Posted (edited)

Other than running 2 scripts at the same time, there's no way to have 2 functions run at the same time. AdLibs don't run at the same time as other functions, they halt the running function, and run the new one, and then when that's done goes back to the original one if I understand it correctly.

Indeed you're right, strictly speaking calling two functions simultaneously is impossible. However running simultaneous processes is possible. If you can trigger two processes to run at the same time it would give that impression. However you need a multi-core processor to truly be running them simultaneously.

Edited by czardas

Share this post


Link to post
Share on other sites

alexlimlexart,

Beside the possibilities offered by the already posted answer, I'd look more closely at why you need such a solution in the first place.

You say querying and having something around 1000 row of your SQLite DB is slow, up to the point you feel the need to parallelize processing. In none of my experiences with SQLite fetching as little as 1000 row is anywhere snail slow as to cause the user take a coffee break. Well, I mean unless you have to run a formidable complex SQL statement or the DB is beyond hundereds of Gb with poor indexing. Both are unlikely for a context where an SQL select "... loads a list of file details".

May I ask you some background detail about your DB schema (including any pragma in force) and the code you use for querying?

I strongly suspect the issue can essentially vanish by fine-tunning the SQL[ite] part.


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)

Share this post


Link to post
Share on other sites

#10 ·  Posted (edited)

Thanks guys for all replies. Jchd, you are probably right but I am now looking into smartee's sample code.

I will be collecting certain inpatient info's from different wards all over the hospital so...

this is assumed that it will reach to about 1000 - 5000 patients in one year.

As a noob in this field (because I am a nurse not a programmer), i fear of losing data so made my Sqlite is very simple.

Each patient will have its own DB3 file and it contains one table and one row and maybe adding one more

table in the future...

The application I am working on right now will do file list to array then read each file, query single row using for loop and

display them in the listview. This is the first approach i could think of fearing of losing huge data if i put it in one DB3 file.

The application will be used by several nurses over the intranet and so making several instances of it from different computers.

The factor that is probably causing the lag is reading several files and not reading a single db3 file but i am more confident in this approach..

Any other suggestions would really help. THANKS!

Edited by alexlimlexart

Share this post


Link to post
Share on other sites

If you're storing patient records, you should probably be looking at a more robust database development solution. Worrying about losing data by having it in a single database file versus separate file for each patient is only one of the factors you should be looking at. How are you securing your data? What is your backup strategy?

And most importantly is, to me at least, what hospital is going to be using this? No offense intended to either the AutoIt development team or to Richard Hipp and the SQLite development team, but I don't want to be a patient there if you are creating a patient tracking solution using AutoIt and SQLite as your development platform.


Whenever someone says "pls" because it's shorter than "please", I say "no" because it's shorter than "yes".

Share this post


Link to post
Share on other sites

#12 ·  Posted (edited)

Alex,

You got about the same fear about DBs that your patients feel right before their surgery! :)

What you've chosen is clearly a terrible solution from a thechnical viewpoint, even if I fully understand why you decided on that.

JohnQSmith is partly right in that a centralized client-server setup is highly recommended in your context. But I also understand that you might not have the admin rights to implement that.

What I disagree is about the alledged lack of robustness of SQLite compared to what comes immediately to mind: MySQL. The latter has many issues that aren't at all on par with a reliable client-server engine. From this point of view, SQLite has much less problems! PostgreSQL is order of magnitude more reliable and stable, but requires even more technical knowledge to setup. Granted, with that low requirements, MySQL can do the job we're talking about easily.

Anyway, it isn't my intention to run into a DB engine flamewar. The problem at hand is that the OP has little choice to implement a satisfactory setup. The AutoIt-SQLite couple isn't the right tool for the job and any client-server engine will demand more priviledges than the OP currently has.

My advice if I may emit one would be to discuss the issue with administrators and hierarchy. If the application is worth its salt, they should find a way to build a decently robust, riskless, supported approach with low setup cost.

Edited by jchd

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)

Share this post


Link to post
Share on other sites

#13 ·  Posted (edited)

Other than running 2 scripts at the same time, there's no way to have 2 functions run at the same time. AdLibs don't run at the same time as other functions, they halt the running function, and run the new one, and then when that's done goes back to the original one if I understand it correctly.

He did not say what the problem he was trying to solve, so I will exercise my psychic ability more. Thanks for the correction.

Edited by DicatoroftheUSA

Share this post


Link to post
Share on other sites

#14 ·  Posted (edited)

Again thanks guys... Well.. I don't have admin rights. This is outside IT department.. mainly involving a small team of nurses that are assigned from different wards. Security isn't an issue because they are the only ones who have access to it. My application will be saved in a shared folder with permissions. Users will only range from 5-10. I chose Autoit and SQlite since these are free and easy to learn at my level of knowledge. If ever this app will be used until next year or so.. then they will be getting huge data...

Situtation:

All db3 files will be staying in one folder (inpatient and discharged file). After my app loads up the db3 files (with sqlite open then shutdown) I tried moving a "no longer needed" db3 file from folder to another folder, but it wouldn't coz its locked.. ending up all db3 in the same place.. and so the app needs to read all files every time it starts.

Edited by alexlimlexart

Share this post


Link to post
Share on other sites

I'll be back to you about this. Please find a good source for some patience.


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)

Share this post


Link to post
Share on other sites

Thank you jchd. In fact, i am very thankful of you. I can wait. =)

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  
Followers 0

  • Similar Content

    • cosmos
      By cosmos
      Edit: Just realised this was posted in the wrong forum! I guess the Mods will move it to either "AutoIt General Help and Support" or "AutoIt Technical Discussion".
      Do you use type checking? Or do you choose not to type check?
      I was trying to think of the simplest way to do a type check without typing arguments more than once and I came up with:
      Func displayPerson($firstName, $lastName, $age) ; -- TYPE CHECK -- Local $typeCheck = ("" _ & IsString($firstName) _ & IsString($lastName) _ & IsNumber($age) _ ) If (StringInStr($typeCheck, "0")) Then MsgBox(16, "Type Error: displayPerson()", $typeCheck) ; -- FUNCTION -- MsgBox(0, "", $firstName & " " & $lastName & " (" & $age & ")") EndFunc The only catch with this method is that it produces a very simplistic error message. Even still, the fact that you only have to type out arguments once makes it a reasonable approach, in my opinion. The same logic can also be used for making function contracts (for example: $firstName mustn't be an empty string etc...).
      What do you think? How do you go about such things?
    • IamKJ
      By IamKJ
      I am trying to allow the GUI to gather info as to when to execute a function.  I am having trouble doing this.  So far this is what I have.
       
      ;Timer Func timer () If Not IsDeclared("iMsgBoxAnswer") Then Local $iMsgBoxAnswer $iMsgBoxAnswer = MsgBox(36,"Timer","Please format your answer in 00:00:00:000") Select Case $iMsgBoxAnswer = 6 ;Yes Global $infotime = InputBox ('Time', 'What time to execute?') Do $rawtimer = ToolTip(@Hour & ':' & @Min & ':' & @Sec & ':' & _MSec()) until $rawtimer = $infotime if $rawtimer = $infotime Then msgbox (0,'Worked','Worked') Else EndIf Case $iMsgBoxAnswer = 7 ;No Exit EndSelect EndFunc Func _MSec() Local $stSystemTime = DllStructCreate('ushort;ushort;ushort;ushort;ushort;ushort;ushort;ushort') DllCall('kernel32.dll', 'none', 'GetSystemTime', 'ptr', DllStructGetPtr($stSystemTime)) $sMilliSeconds = StringFormat('%03d', DllStructGetData($stSystemTime, 8)) $stSystemTime = 0 Return $sMilliSeconds EndFunc I have also tried _GUIToolTip_GetText in order to read the tooltip until the time specified, but it still doesn't work.  Any help would be great.
    • XOblivion
      By XOblivion
      im some what new to autoit and need help figuring out best way to make a simple clicker for few idle games i play(taptitdue, sakura clicker, elndless frontier etc.) ive played around with autoit recorder to make simple copy mouse clicks. but now i want to make a script that allows me to select multiple functions before starting the script for game ex: click section A or click section A + B to run At set intervals if that makes sense . i dont need scripts made by other just info on what things i should use to make it my self.
       
      need to be able to select between games and be able to select multiple functions to run inconjuntion or independent for each game. thank you in advance
    • BetaLeaf
      By BetaLeaf
      Hi guys. I am trying to make a soundboard app. 
      Here is the code I have so far
      #include "Misc.au3" #RequireAdmin;needed to work in some games. #include "array.au3" Opt("WinTitleMatchMode", -2) If @OSArch = "x64" Then Global $VLC_Path = "C:\Program Files (x86)\VideoLAN\VLC\vlc.exe" Global $VLC_WorkingDir = "C:\Program Files (x86)\VideoLAN\VLC\" Else Global $VLC_Path = "C:\Program Files\VideoLAN\VLC\vlc.exe" Global $VLC_WorkingDir = "C:\Program Files\VideoLAN\VLC\" EndIf Global $sectionData = IniReadSectionNames(@ScriptDir & "\SoundBoard.ini") If @error Then IniWriteSection(@ScriptDir & "\SoundBoard.ini", "Sound1", 'File="' & @UserProfileDir & '\Music\SampleTrack.mp3"' & @CRLF & 'StartTime="12"' & @CRLF & 'EndTime="34"' & @CRLF & 'PlaybackDevice="Microsoft Soundmapper"' & @CRLF & 'Hotkey="+{numpad9}"') MsgBox(16, "SoundBoard", "SoundBoard.ini is missing. It has been created for you.") ShellExecute(@ScriptDir & "\SoundBoard.ini", "", "", "edit") InputBox("SoundBoard", "Notes:" & @CRLF & "StartTime and EndTime are in seconds. Available Hotkeys can be found at the following url:", "https://www.autoitscript.com/autoit3/docs/functions/Send.htm") Exit EndIf For $i = 1 To $sectionData[0] Local $iArray = IniReadSection(@ScriptDir & "\SoundBoard.ini", $sectionData[$i]) For $j = 1 To UBound($iArray) - 1 Local $result = Assign("SoundBoard" & $i & "_" & $j, IniRead(@ScriptDir & "\SoundBoard.ini", $sectionData[$i], $iArray[$j][0], $iArray[$j][1]), 2) If $result = 1 Then Consolewrite("Variable Assigned: SoundBoard" & $i & "_" & $j & @CRLF & "Data=" & $iArray[$j][1]&@CRLF) Else Consolewrite("Variable was not assigned: SoundBoard" & $i & "_" & $j & @CRLF & "Data=" & $iArray[$j][1]&@CRLF) EndIf Next Next For $i = 1 To $sectionData[0] Local $Hotkey = Eval("SoundBoard"&$i&"_5") ConsoleWrite("Processing Hotkey "&$Hotkey&@CRLF) ;NEED HELP HERE ; HotKeySet($Hotkey,"") Next While 1 Sleep(500);idle to prevent unnecessary work. 10 is the minimal we can set this value to. WEnd Func LoadVLC($iPlayFile, $iPlayFileStartTime, $iPlayFileEndTime, $iPlayAudioDevice = "Microsoft Soundmapper") ShellExecuteWait($VLC_Path, '--qt-start-minimized --play-and-exit --start-time="' & $iPlayFileStartTime & '" --stop-time="' & $iPlayFileEndTime & '" --aout=waveout --waveout-audio-device="' & $iPlayAudioDevice & '" "' & $iPlayFile & '"', $VLC_WorkingDir, "", @SW_HIDE) Beep(500, 200) EndFunc ;==>LoadVLC For example, I have a song called "MoonlightSonata.mp3" and I want to activate it with hotkey !{numpad9}. However, hotkeyset does not allow sending of flags so I cannot use LoadVLC as it is now. I need to create a function that stores the flags using the data from the earlier Inireads. Ik how to use the data but not how to create the function to store that data. I looked at IsFunc() second example but I do not understand. Sorry if I am not being clear on what I am trying to do. My brain is fried right now after trying various things for an hour. Any help would be appreciated. 
      The idea is to be able to have a dedicated hotkey for each sound I want to play so I will need to have my script create a new function by itself using the data from the INI.
      hotkeyset("$hotkey1","MySoundBoard1") hotkeyset("$hotkey2","MySoundBoard2") func MySoundBoard1() LoadVLC("MoonlightSonata.mp3") ;the other flags are optional and will not be set for simplicity. endfunc func MySoundBoard1() LoadVLC("TheBananaSong.mp3") endfunc Honestly I don't care how it is done as long as I have a dedicated hotkey for each entry in my ini.  An example of such an entry looks like
      [Sound1] File="C:\Users\BetaL\Music\SampleTrack1.mp3" StartTime="12" EndTime="34" PlaybackDevice="Microsoft Soundmapper" Hotkey="!{numpad8}" [Sound2] File="C:\Users\BetaL\Music\SampleTrack2.mp3" StartTime="24" EndTime="43" PlaybackDevice="Microsoft Soundmapper" Hotkey="!{numpad9}" Am I making any sense? Please let me know.
       
      Edit: Huge thanks to @Melba23 for the learning experience, his time, and help.
    • dynamitemedia
      By dynamitemedia
      i have the following snippet...   now its working but i have it inside a function and want to be able to use   $aThumb[$i]  outside the function in the rest of the script, i tried return and keep getting this error  "Invalid keyword at the start of this line.:"  
      Global $iRows = UBound($a, $UBOUND_ROWS) Global $iCols = UBound($a, $UBOUND_COLUMNS) $oID = $oID + 1 $oURL = $oString.selectSingleNode("./url") $oName = $oString.selectSingleNode("./name") $oCategory = $oString.selectSingleNode("./category") $oThumb = $oString.selectSingleNode("./image") $oLanguage = $oString.selectSingleNode("./language") $aThumb = [$iRows] _ArrayAdd($aThumb, $oThumb.text) For $i = 1 To UBound($aThumb) - 1 ConsoleWrite($oID & @TAB & $aThumb[$i] & @CRLF) Next Next ConsoleWrite( "rows: " & $iRows & @CRLF) Thanks for your help