因爲在不引入信號和多線程的情況下獨立等待來管理多個函數並不容易,下面是用PyAutoGUI
庫管理多個函數的另一種方法。
的解決方案是一個多定序器類(稱爲class TimerExec
)。
步驟1 - 使用class TimerSeq
存儲序參數
只需要構造
class TimerSeq:
def __init__(self, iseq, tseq, bexe, bloop):
self.iseq = iseq
self.tseq = tseq
self.bexe = bexe
self.bloop = bloop
步驟2 - 創建class TimerExec
管理列表測序儀
構造函數創建一個空的列表
class TimerExec:
def __init__(self):
self.list = [ ]
self.stop = True
self.chrono = -1
self.delay = -1
一個簡單的浮點秒值爲int毫秒
#
# convert float seconds to milliseconds
def tomilli(self, fsec):
return int(round(fsec * 1000))
添加一個新的序列表
#
# append new sequences to the list
def append(self, func, loop=False):
self.list.append([func, TimerSeq(-1, -1, False, loop)])
print('list:',self.list)
驗證如果定序器是完全的或重新啓動時環
#
# check end of sequence or restart
def nextcheck(self, seq):
if seq[1].iseq >= len(seq[0]):
if seq[1].bloop:
seq[1].iseq = 0 # restart
return True
return False
計算參數爲下一個序列中的當前音序
#
# switch to the next sequence
def nextstep(self, seq):
if seq[1].iseq >= len(seq[0]):
return True
seq[1].iseq = seq[1].iseq+1
seq[1].tseq = self.tomilli(time.time())
seq[1].bexe = False
return False
管理當前序器和執行當前的功能,那麼 延遲下一序列
#
# explore sequence and execute when
def exestep(self, seq):
bseq = False
if seq[1].tseq < 0:
bseq = self.nextstep(seq)
else:
bseq = self.nextcheck(seq)
if bseq:
return True
pseq = seq[0][seq[1].iseq]
tnow = self.tomilli(time.time())
tdel = self.tomilli(pseq[0])
if seq[1].bexe == False:
print('execute(%d):'% (tnow-self.chrono),pseq)
# execute the selected function
pseq[1](pseq[2],pseq[3],pseq[4])
seq[1].bexe = True
tseq = seq[1].tseq
if tnow > (tseq+tdel):
bseq = self.nextstep(seq)
return bseq
主迴路功能,探索所有音序器,直到完成或 max_delay
#
# loop to execute all sequences with max_delay (s)
def execute(self, max_delay):
print('start:',time.strftime("%H:%M:%S", time.localtime()))
self.stop = False
self.delay = self.tomilli(max_delay)
self.chrono = self.tomilli(time.time())
while self.stop == False:
tnow = self.tomilli(time.time())
#if tnow > (self.chrono + self.delay):
# break
bstop = True
for seq in self.list:
bseq = self.exestep(seq)
bstop = bstop & bseq
if bstop == True:
self.stop = True
print('stop:',time.strftime("%H:%M:%S", time.localtime()),
((tnow-self.chrono)/1000.0))
步驟3 - 根據您聲明的功能聲明您的音序器
對於功能1(),使用2步序:
def function1():
pyautogui.click(button='left', x=619, y=266)
pyautogui.PAUSE = 3.9
pyautogui.click(button='left', x=617, y=475)
定序是:
fct1 = [
# pyautogui.click(button='left', x=619, y=266)
[ 3.9, pyautogui.click, 'left', 619, 266 ],
# pyautogui.click(button='left', x=617, y=475)
[ 0.0, pyautogui.click, 'left', 617, 475 ]
]
步驟4 - 創建TimerExec對象,添加序然後執行。
持續時間限制爲13。6秒最大
tSeq = TimerExec()
tSeq.append(fct1)
tSeq.execute(13.6)
具有u試圖導入時間,然後使用time.sleep(x)的x是幾秒鐘的延遲的數量。 –
這意味着我應該讓它沒有功能,對吧? –
但是,如果我這樣做,那麼函數1運行代碼,然後睡15(不做任何事),然後function2開始,這不是重點。我想function1作爲循環運行15分鐘,然後運行一次函數2並返回到function1作爲循環... –