Подскажите с задачкой, требуется таймер, который будет выполняться в полной независимости от остального кода. По истечению времени будет выполняться действие. Т.е. Таймер должен работать независимо от самого скрипта, ровно как 2 макроса [скрипт] и [таймер] единовременно.
winipox, AutoIt — однопоточное приложение. Так что и делайте два макроса. Либо согласитесь на то, что при работе процедуры обработки события тайминга основное приложение будет временно «заморожено».
madmasles
30-11-2011, 00:09
основное приложение будет временно «заморожено». »Смотря что будет делать основное приложение. В некоторых случаях можно использовать _Timer_SetTimer().
В некоторых случаях можно использовать _Timer_SetTimer(). »
И…? Поясните, это сделает возможным в одном скрипте AutoIt исполнение процедуры и, одновременно, продолжение исполнения основного кода скрипта?
madmasles
30-11-2011, 11:22
Iska,
Пример. Одновременно работают основной цикл, часы, прогресс и его строковое значение. При этом можно прервать цикл или выйти из программы (если выход во время работы цикла, то код выхода 1).#include (http://www.autoitscript.com/autoit3/docs/keywords.htm##include) <WindowsConstants.au3>
#include (http://www.autoitscript.com/autoit3/docs/keywords.htm##include) <GuiConstantsEx.au3>
#include (http://www.autoitscript.com/autoit3/docs/keywords.htm##include) <Timers.au3>
#include (http://www.autoitscript.com/autoit3/docs/keywords.htm##include) <GuiStatusBar.au3>
#include (http://www.autoitscript.com/autoit3/docs/keywords.htm##include) <ProgressConstants.au3>
#include (http://www.autoitscript.com/autoit3/docs/keywords.htm##include) <EditConstants.au3>
#include (http://www.autoitscript.com/autoit3/docs/keywords.htm##include) <MenuConstants.au3>
Global (http://www.autoitscript.com/autoit3/docs/keywords.htm#Global) $nMemo, $hStatusBar, $nProgress, $iPercent = 0, $direction = 1, $aParts[3] = [100, 300, -1], _
$nBtn_start, $nBtn_stop, $iTimerProgress, $iStart, $iTimeOut = 60000, $fWork, $fStop
$hGUI = GUICreate (http://www.autoitscript.com/autoit3/docs/functions/GUICreate.htm)('Test Func _Timer_SetTimer()', 400, 320, -1, -1, -1, $WS_EX_TOOLWINDOW)
$nMemo = GUICtrlCreateEdit (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlCreateEdit.htm)('', 2, 32, 396, 226, BitOR (http://www.autoitscript.com/autoit3/docs/functions/BitOR.htm)($WS_HSCROLL, $WS_VSCROLL, $ES_READONLY))
GUICtrlSetFont (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlSetFont.htm)($nMemo, 9, 400, 0, 'Courier New')
$nBtn_start = GUICtrlCreateButton (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlCreateButton.htm)('Start', 70, 265, 100, 25)
$nBtn_stop = GUICtrlCreateButton (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlCreateButton.htm)('Stop', 215, 265, 90, 25)
GUICtrlSetState (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlSetState.htm)(-1, $GUI_DISABLE)
$hStatusBar = _GUICtrlStatusBar_Create (http://dundats.mvps.org/help/html/libfunctions/_guictrlstatusbar_create.htm)($hGUI, $aParts)
_GUICtrlStatusBar_SetText (http://dundats.mvps.org/help/html/libfunctions/_guictrlstatusbar_settext.htm)($hStatusBar, @TAB (http://www.autoitscript.com/autoit3/docs/macros.htm#@tab) & StringFormat (http://www.autoitscript.com/autoit3/docs/functions/StringFormat.htm)('%02d:%02d:%02d', @HOUR (http://www.autoitscript.com/autoit3/docs/macros.htm#@hour), @MIN (http://www.autoitscript.com/autoit3/docs/macros.htm#@min), @SEC (http://www.autoitscript.com/autoit3/docs/macros.htm#@sec)), 2)
$nProgress = GUICtrlCreateProgress (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlCreateProgress.htm)(0, 0, -1, -1, $PBS_SMOOTH)
_GUICtrlStatusBar_EmbedControl (http://dundats.mvps.org/help/html/libfunctions/_guictrlstatusbar_embedcontrol.htm)($hStatusBar, 1, GUICtrlGetHandle (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlGetHandle.htm)($nProgress))
GUICtrlSetState (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlSetState.htm)($nProgress, $GUI_HIDE)
GUISetState (http://www.autoitscript.com/autoit3/docs/functions/GUISetState.htm)()
GUIRegisterMsg (http://www.autoitscript.com/autoit3/docs/functions/GUIRegisterMsg.htm)($WM_COMMAND, 'WM_COMMAND')
GUIRegisterMsg (http://www.autoitscript.com/autoit3/docs/functions/GUIRegisterMsg.htm)($WM_SYSCOMMAND, 'WM_SYSCOMMAND')
_Timer_SetTimer (http://dundats.mvps.org/help/html/libfunctions/_timer_settimer.htm)($hGUI, 1000, '_UpdateStatusBarClock')
While (http://www.autoitscript.com/autoit3/docs/keywords.htm#While) 1
Switch (http://www.autoitscript.com/autoit3/docs/keywords.htm#Switch) GUIGetMsg (http://www.autoitscript.com/autoit3/docs/functions/GUIGetMsg.htm)()
Case (http://www.autoitscript.com/autoit3/docs/keywords.htm#Case) $GUI_EVENT_CLOSE
ExitLoop (http://www.autoitscript.com/autoit3/docs/keywords.htm#ExitLoop)
Case (http://www.autoitscript.com/autoit3/docs/keywords.htm#Case) $nBtn_start
$fWork = True (http://www.autoitscript.com/autoit3/docs/keywords.htm#True)
$fStop = False (http://www.autoitscript.com/autoit3/docs/keywords.htm#False)
$iStart = TimerInit (http://www.autoitscript.com/autoit3/docs/functions/TimerInit.htm)()
GUICtrlSetData (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlSetData.htm)($nProgress, 0)
GUICtrlSetState (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlSetState.htm)($nProgress, $GUI_SHOW)
GUICtrlSetState (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlSetState.htm)($nBtn_stop, $GUI_ENABLE)
GUICtrlSetState (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlSetState.htm)($nBtn_start, $GUI_DISABLE)
GUICtrlSetData (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlSetData.htm)($nMemo, '')
$iTimerProgress = _Timer_SetTimer (http://dundats.mvps.org/help/html/libfunctions/_timer_settimer.htm)($hGUI, 100, '_UpdateProgressBar')
_BasicCycle()
EndSwitch (http://www.autoitscript.com/autoit3/docs/keywords.htm#EndSwitch)
WEnd (http://www.autoitscript.com/autoit3/docs/keywords.htm#WEnd)
Func (http://www.autoitscript.com/autoit3/docs/keywords.htm#Func) _BasicCycle()
;основной цикл для примера
Local (http://www.autoitscript.com/autoit3/docs/keywords.htm#Local) $i_Count = 0, $s_Mess
MemoWrite('Основной цикл будет работать ' & StringFormat (http://www.autoitscript.com/autoit3/docs/functions/StringFormat.htm)('%d сек.', $iTimeOut / 1000) & @CRLF (http://www.autoitscript.com/autoit3/docs/macros.htm#@crlf))
MemoWrite('Его можно прервать, нажав кнопку "Stop".' & @CRLF (http://www.autoitscript.com/autoit3/docs/macros.htm#@crlf))
MemoWrite('~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~' & @CRLF (http://www.autoitscript.com/autoit3/docs/macros.htm#@crlf))
MemoWrite('Работает основной цикл.' & @CRLF (http://www.autoitscript.com/autoit3/docs/macros.htm#@crlf))
While (http://www.autoitscript.com/autoit3/docs/keywords.htm#While) 1
$i_Count += 1
$s_Mess = $i_Count & ','
If (http://www.autoitscript.com/autoit3/docs/keywords.htm#If) Not (http://www.autoitscript.com/autoit3/docs/keywords.htm#Not) Mod (http://www.autoitscript.com/autoit3/docs/functions/Mod.htm)($i_Count, 12) Then (http://www.autoitscript.com/autoit3/docs/keywords.htm#Then) $s_Mess &= @CRLF (http://www.autoitscript.com/autoit3/docs/macros.htm#@crlf)
MemoWrite($s_Mess)
Sleep (http://www.autoitscript.com/autoit3/docs/functions/Sleep.htm)(Random (http://www.autoitscript.com/autoit3/docs/functions/Random.htm)(100, 500, 1))
If (http://www.autoitscript.com/autoit3/docs/keywords.htm#If) Not (http://www.autoitscript.com/autoit3/docs/keywords.htm#Not) $fWork Then (http://www.autoitscript.com/autoit3/docs/keywords.htm#Then) ExitLoop (http://www.autoitscript.com/autoit3/docs/keywords.htm#ExitLoop)
If (http://www.autoitscript.com/autoit3/docs/keywords.htm#If) $fStop Then (http://www.autoitscript.com/autoit3/docs/keywords.htm#Then) ExitLoop (http://www.autoitscript.com/autoit3/docs/keywords.htm#ExitLoop)
WEnd (http://www.autoitscript.com/autoit3/docs/keywords.htm#WEnd)
_Timer_KillTimer (http://dundats.mvps.org/help/html/libfunctions/_timer_killtimer.htm)($hGUI, $iTimerProgress)
GUICtrlSetState (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlSetState.htm)($nProgress, $GUI_HIDE)
GUICtrlSetState (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlSetState.htm)($nBtn_stop, $GUI_DISABLE)
GUICtrlSetState (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlSetState.htm)($nBtn_start, $GUI_ENABLE)
If (http://www.autoitscript.com/autoit3/docs/keywords.htm#If) $fStop Then (http://www.autoitscript.com/autoit3/docs/keywords.htm#Then)
MemoWrite(@CRLF (http://www.autoitscript.com/autoit3/docs/macros.htm#@crlf) & '~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~' & @CRLF (http://www.autoitscript.com/autoit3/docs/macros.htm#@crlf))
MemoWrite('Основной цикл прерван пользователем.' & @CRLF (http://www.autoitscript.com/autoit3/docs/macros.htm#@crlf))
Else (http://www.autoitscript.com/autoit3/docs/keywords.htm#Else)
MemoWrite(@CRLF (http://www.autoitscript.com/autoit3/docs/macros.htm#@crlf) & '~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~=~' & @CRLF (http://www.autoitscript.com/autoit3/docs/macros.htm#@crlf))
MemoWrite('Основной цикл закончен по таймауту.' & @CRLF (http://www.autoitscript.com/autoit3/docs/macros.htm#@crlf))
EndIf (http://www.autoitscript.com/autoit3/docs/keywords.htm#EndIf)
EndFunc (http://www.autoitscript.com/autoit3/docs/keywords.htm#EndFunc) ;==>_BasicCycle
Func (http://www.autoitscript.com/autoit3/docs/keywords.htm#Func) _UpdateStatusBarClock($hWnd, $Msg, $iIDTimer, $dwTime)
#forceref $hWnd, $Msg, $iIDTimer, $dwTime
_GUICtrlStatusBar_SetText (http://dundats.mvps.org/help/html/libfunctions/_guictrlstatusbar_settext.htm)($hStatusBar, @TAB (http://www.autoitscript.com/autoit3/docs/macros.htm#@tab) & StringFormat (http://www.autoitscript.com/autoit3/docs/functions/StringFormat.htm)('%02d:%02d:%02d', @HOUR (http://www.autoitscript.com/autoit3/docs/macros.htm#@hour), @MIN (http://www.autoitscript.com/autoit3/docs/macros.htm#@min), @SEC (http://www.autoitscript.com/autoit3/docs/macros.htm#@sec)), 2)
EndFunc (http://www.autoitscript.com/autoit3/docs/keywords.htm#EndFunc) ;==>_UpdateStatusBarClock
Func (http://www.autoitscript.com/autoit3/docs/keywords.htm#Func) _UpdateProgressBar($hWnd, $Msg, $iIDTimer, $dwTime)
#forceref $hWnd, $Msg, $iIDTimer, $dwTime
Local (http://www.autoitscript.com/autoit3/docs/keywords.htm#Local) $s_Mess, $i_Diff
$i_Diff = TimerDiff (http://www.autoitscript.com/autoit3/docs/functions/TimerDiff.htm)($iStart)
$iPercent = Int (http://www.autoitscript.com/autoit3/docs/functions/Int.htm)(100 * $i_Diff / $iTimeOut)
$s_Mess = StringFormat (http://www.autoitscript.com/autoit3/docs/functions/StringFormat.htm)('%.1f сек(%02d%)', $i_Diff / 1000, $iPercent)
If (http://www.autoitscript.com/autoit3/docs/keywords.htm#If) $iPercent = 100 Then (http://www.autoitscript.com/autoit3/docs/keywords.htm#Then)
$fWork = False (http://www.autoitscript.com/autoit3/docs/keywords.htm#False)
$s_Mess = StringFormat (http://www.autoitscript.com/autoit3/docs/functions/StringFormat.htm)('%.1f сек(%02d%)', $iTimeOut / 1000, $iPercent)
EndIf (http://www.autoitscript.com/autoit3/docs/keywords.htm#EndIf)
GUICtrlSetData (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlSetData.htm)($nProgress, $iPercent)
_GUICtrlStatusBar_SetText (http://dundats.mvps.org/help/html/libfunctions/_guictrlstatusbar_settext.htm)($hStatusBar, @TAB (http://www.autoitscript.com/autoit3/docs/macros.htm#@tab) & $s_Mess, 0)
EndFunc (http://www.autoitscript.com/autoit3/docs/keywords.htm#EndFunc) ;==>_UpdateProgressBar
Func (http://www.autoitscript.com/autoit3/docs/keywords.htm#Func) MemoWrite($s_Message)
GUICtrlSetData (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlSetData.htm)($nMemo, $s_Message, 1)
EndFunc (http://www.autoitscript.com/autoit3/docs/keywords.htm#EndFunc) ;==>MemoWrite
Func (http://www.autoitscript.com/autoit3/docs/keywords.htm#Func) WM_SYSCOMMAND($hWnd, $Msg, $wParam, $lParam)
Local (http://www.autoitscript.com/autoit3/docs/keywords.htm#Local) $nID = BitAND (http://www.autoitscript.com/autoit3/docs/functions/BitAND.htm)($wParam, 0xFFFF)
Switch (http://www.autoitscript.com/autoit3/docs/keywords.htm#Switch) $nID
Case (http://www.autoitscript.com/autoit3/docs/keywords.htm#Case) $SC_CLOSE
If (http://www.autoitscript.com/autoit3/docs/keywords.htm#If) $fWork Then (http://www.autoitscript.com/autoit3/docs/keywords.htm#Then) Exit (http://www.autoitscript.com/autoit3/docs/keywords.htm#Exit) 1
Exit (http://www.autoitscript.com/autoit3/docs/keywords.htm#Exit)
EndSwitch (http://www.autoitscript.com/autoit3/docs/keywords.htm#EndSwitch)
Return (http://www.autoitscript.com/autoit3/docs/keywords.htm#Return) $GUI_RUNDEFMSG
EndFunc (http://www.autoitscript.com/autoit3/docs/keywords.htm#EndFunc) ;==>WM_SYSCOMMAND
Func (http://www.autoitscript.com/autoit3/docs/keywords.htm#Func) WM_COMMAND($hWnd, $Msg, $wParam, $lParam)
Local (http://www.autoitscript.com/autoit3/docs/keywords.htm#Local) $nID = BitAND (http://www.autoitscript.com/autoit3/docs/functions/BitAND.htm)($wParam, 0xFFFF)
Switch (http://www.autoitscript.com/autoit3/docs/keywords.htm#Switch) $nID
Case (http://www.autoitscript.com/autoit3/docs/keywords.htm#Case) $nBtn_stop
$fStop = True (http://www.autoitscript.com/autoit3/docs/keywords.htm#True)
$fWork = False (http://www.autoitscript.com/autoit3/docs/keywords.htm#False)
EndSwitch (http://www.autoitscript.com/autoit3/docs/keywords.htm#EndSwitch)
Return (http://www.autoitscript.com/autoit3/docs/keywords.htm#Return) $GUI_RUNDEFMSG
EndFunc (http://www.autoitscript.com/autoit3/docs/keywords.htm#EndFunc) ;==>WM_COMMAND
winipox,
Предупреждение за нарушение правил форума, пункт 2.7 (http://forum.oszone.net/rules.html#2.7) и пункт 3.19 (http://forum.oszone.net/rules.html#3.19):
2.7: В заголовке темы обязательно обозначайте название предмета, которого касается вопрос, а в теле сообщения максимально подробно опишите проблему (приведите аппаратную/программную конфигурацию, а также изложите ситуацию, в которой возникает проблема)...
Подробнее о принципах создания тем читайте в этом документе (http://forum.oszone.net/faq.php?faq=vb_read_and_post#faq_thread) и Правилах форумов.
3.19: Запрещается... Создавать темы, имеющие неинформативные или состоящие из заглавных букв заголовки (например, "Помогите!", "HELP!", "У меня проблема"). Такие темы будут закрыты или перенесены в Тест-форум. Если вы хотите вернуть перенесенную тему обратно, пока ее не закрыли в Тест-форуме, измените ее заголовок на осмысленный (http://forum.oszone.net/faq.php?faq=vb_board_usage#faq_rename_thread) и напишите об этом в теме.
Переименуйте пожалуйста тему (Как переименовать свою тему? (http://forum.oszone.net/faq.php?faq=vb_board_usage#faq_rename_thread)).
madmasles, Вы меня не поняли. Добавьте, например, в обработку вычиcления пообъёмнее, даже хотя бы симулировать банально Sleep()'ом:
Func _UpdateProgressBar($hWnd, $Msg, $iIDTimer, $dwTime)
…
Sleep(5000)
EndFunc ;==>_UpdateProgressBar
и что получится с основным циклом? Понимаете меня? То есть, это:
Либо согласитесь на то, что при работе процедуры обработки события тайминга основное приложение будет временно «заморожено». »
madmasles
30-11-2011, 23:53
Iska,
Я Вас и сейчас не понимаю. Что значит вычисления пообъёмнее? Пример? Зачем в функцию _UpdateProgressBar() добавлять Sleep(5000)?
madmasles, для того, чтобы показать, что при работе процедуры выполнение основного кода скрипта будет приостановлено до её завершения.
madmasles
01-12-2011, 08:51
для того, чтобы показать, что при работе процедуры выполнение основного кода скрипта будет приостановлено до её завершения. »Зачем? Код же работает.
PS
С помощью Sleep() можно много чего испортить, например:#include (http://www.autoitscript.com/autoit3/docs/keywords.htm##include) <GuiConstantsEx.au3>
$hGui = GUICreate (http://www.autoitscript.com/autoit3/docs/functions/GUICreate.htm)('Test')
$nBtn = GUICtrlCreateButton (http://www.autoitscript.com/autoit3/docs/functions/GUICtrlCreateButton.htm)('Test', 20, 20)
GUISetState (http://www.autoitscript.com/autoit3/docs/functions/GUISetState.htm)()
While (http://www.autoitscript.com/autoit3/docs/keywords.htm#While) 1
$nMsg = GUIGetMsg (http://www.autoitscript.com/autoit3/docs/functions/GUIGetMsg.htm)()
Switch (http://www.autoitscript.com/autoit3/docs/keywords.htm#Switch) $nMsg
Case (http://www.autoitscript.com/autoit3/docs/keywords.htm#Case) $GUI_EVENT_CLOSE
Exit (http://www.autoitscript.com/autoit3/docs/keywords.htm#Exit)
Case (http://www.autoitscript.com/autoit3/docs/keywords.htm#Case) $nBtn
MsgBox (http://www.autoitscript.com/autoit3/docs/functions/MsgBox.htm)(64, 'Info', 'Click', 0, $hGui)
EndSwitch (http://www.autoitscript.com/autoit3/docs/keywords.htm#EndSwitch)
;Sleep(1000);раскомментируйте строку и скрипт не будет работать.
WEnd (http://www.autoitscript.com/autoit3/docs/keywords.htm#WEnd)
Зачем? Код же работает. »
Работает. Но не независимо. Что я и пытался показать на примере.
С помощью Sleep() можно много чего испортить, например: »
Это не тот пример ;). Я же задерживал исполнение процедуры обработки — и оказывалось, что основной код во время работы процедуры — не работает, а «стоит» и «ждёт» окончания обработки.
Смотрите:
требуется таймер, который будет выполняться в полной независимости от остального кода. … Таймер должен работать независимо от самого скрипта, ровно как 2 макроса [скрипт] и [таймер] единовременно. »
Одновременно работают основной цикл, часы, прогресс и его строковое значение. »
Достаточно добавить в процедуру обработки таймера какие-либо массивные вычисления, долгий код (Sleep() — это только для примера), и сразу становится ясно, что никакой одновременной, никакой независимой друг от друга работы основного кода и процедуры обработки таймера нет. О чём я и написал во втором посте темы. О чём явно написано в другом примере — AdlibRegister (http://www.autoitscript.com/autoit3/docs/functions/AdlibRegister.htm):
The adlib function should be kept simple as it is executed often and during this time the main script is paused.
Вы просто меня не поняли ;).
Автор что-то молчит. Я-то думаю, что для его целей наверняка хватит и существующей технологии квази-независимой обработки.
vBulletin v3.6.4, Copyright ©2000-2025, Jelsoft Enterprises Ltd.