threading.Timer - 'n' 秒ごとに関数を繰り返す 質問する

threading.Timer - 'n' 秒ごとに関数を繰り返す 質問する

0.5 秒ごとに関数を起動し、タイマーを開始、停止、リセットできるようにしたいと考えています。Python スレッドの動作についてあまり詳しくなく、Python タイマーで問題を抱えています。

しかし、 2 回RuntimeError: threads can only be started once実行すると、同じエラーが引き続き発生しますthreading.timer.start()。この問題を回避する方法はありますか?threading.timer.cancel()起動する前に毎回適用してみました。

疑似コード:

t=threading.timer(0.5,function)
while True:
    t.cancel()
    t.start()

ベストアンサー1

最も良い方法は、タイマースレッドを一度起動することです。タイマースレッド内では、次のようにコーディングします。

class MyThread(Thread):
    def __init__(self, event):
        Thread.__init__(self)
        self.stopped = event

    def run(self):
        while not self.stopped.wait(0.5):
            print("my thread")
            # call a function

タイマーを開始したコードでは、set停止イベントを使用してタイマーを停止できます。

stopFlag = Event()
thread = MyThread(stopFlag)
thread.start()
# this will stop the timer
stopFlag.set()

おすすめ記事