標籤:nis not 調用函數 read 資源 \n waiting python 個人
項目中需要使用定時器,每次都使用構造器函數調用:
timer = threading.Timer(timerFlag, upload_position)timer.start()
列印線程後發現,每次都會建立一個新的子線程,雖然活躍的線程只有一個,但是也是種資源浪費:
print("threading active = {} \n \n".format(threading.enumerate()))#列印threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145498161152)>]threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145498161152)>]threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145498161152)>]threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-2, started 123145503416320)>]threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-2, started 123145503416320)>]threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-3, started 123145498161152)>]threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-3, started 123145498161152)>]
閱讀源碼和文檔
class Timer(Thread): """Call a function after a specified number of seconds: t = Timer(30.0, f, args=None, kwargs=None) t.start() t.cancel() # stop the timer's action if it's still waiting """ def __init__(self, interval, function, args=None, kwargs=None): Thread.__init__(self) self.interval = interval self.function = function self.args = args if args is not None else [] self.kwargs = kwargs if kwargs is not None else {} self.finished = Event() def cancel(self): """Stop the timer if it hasn't finished yet.""" self.finished.set() def run(self): self.finished.wait(self.interval) if not self.finished.is_set(): self.function(*self.args, **self.kwargs) self.finished.set()# Special thread class to represent the main thread# This is garbage collected through an exit handler
發現,其實Timer是threading的子類,用wait實現了定時效果,綁定了入參function,於是修改代碼如下
def startTimer(): global timer if timer != None: timer.finished.wait(timerFlag) timer.function() else: timer = threading.Timer(timerFlag, upload_position) timer.start()
列印結果:
threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]threading active = [<_MainThread(MainThread, stopped 140735596835712)>, <Timer(Thread-1, started 123145516048384)>]
始終只有一個線程且重複調用函數方法~End~
? ?
? ?
? ?
友情連結:個人網站???????技術部落格 ???????簡書首頁
Python threading 單線程 timer重複調用函數