Python threading.timer-'n'秒ごとに関数を繰り返す


94

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()

回答:


112

最善の方法は、タイマースレッドを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、stoppedイベントを使用してタイマーを停止できます。

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

4
それからそれはそれが睡眠で終わって、その後止まります。Pythonでスレッドを強制的に中断する方法はありません。これは、Python開発者が行った設計上の決定です。ただし、最終結果は同じになります。スレッドはしばらくの間(スリープ)実行されますが、機能は実行されません。
Hans Then

13
まあ、実際には、タイマースレッドをすぐに停止できるようにする場合はthreading.Event、のwait代わりにとを使用しsleepます。次に、それを起こすには、イベントを設定します。self.stoppedイベントフラグをチェックするだけなので、thenは必要ありません。
nneonneo 2012

3
イベントは、タイマースレッドを中断するために厳密に使用されます。通常、はevent.waitタイムアウトしてスリープのように動作しますが、停止(またはスレッドを中断)したい場合は、スレッドのイベントを設定するとすぐに起動します。
nneonneo 2012

2
event.wait()を使用するように回答を更新しました。提案をありがとう。
Hans Then

1
質問ですが、その後スレッドを再起動するにはどうすればよいですか?呼び出しthread.start()は私に与えるthreads can only be started once
Motassem MK 2017

33

PythonのsetIntervalの同等のものから:

import threading

def setInterval(interval):
    def decorator(function):
        def wrapper(*args, **kwargs):
            stopped = threading.Event()

            def loop(): # executed in another thread
                while not stopped.wait(interval): # until stopped
                    function(*args, **kwargs)

            t = threading.Thread(target=loop)
            t.daemon = True # stop if the program exits
            t.start()
            return stopped
        return wrapper
    return decorator

使用法:

@setInterval(.5)
def function():
    "..."

stop = function() # start timer, the first call is in .5 seconds
stop.set() # stop the loop
stop = function() # start new timer
# ...
stop.set() 

または、これは同じ機能ですが、デコレータの代わりにスタンドアロン関数として

cancel_future_calls = call_repeatedly(60, print, "Hello, World")
# ...
cancel_future_calls() 

スレッドを使用せずにそれを行う方法は次のとおりです。


デコレータを使用するときに間隔をどのように変更しますか?実行時に.5sを1秒または何に変更したいですか?
lightxx 2013

@lightxx:だけを使用してください@setInterval(1)
jfs 2013

うーん。だから私は少し遅いかあなたは私を誤解しました。実行時に意味しました。私はいつでもソースコードのデコレータを変更できることを知っています。たとえば、3つの関数があり、それぞれ@setInterval(n)で装飾されています。ここで、実行時に関数2の間隔を変更しますが、関数1と3はそのままにしておきます。
lightxx 2013

@lightxx:など、別のインターフェースを使用できますstop = repeat(every=second, call=your_function); ...; stop()
jfs 2013

1
@lightxx:ここでは非デコレータだstop = call_repeatedly(interval, your_function); ...; stop()実装は
JFS

31

タイマースレッドの使用

from threading import Timer,Thread,Event


class perpetualTimer():

   def __init__(self,t,hFunction):
      self.t=t
      self.hFunction = hFunction
      self.thread = Timer(self.t,self.handle_function)

   def handle_function(self):
      self.hFunction()
      self.thread = Timer(self.t,self.handle_function)
      self.thread.start()

   def start(self):
      self.thread.start()

   def cancel(self):
      self.thread.cancel()

def printer():
    print 'ipsem lorem'

t = perpetualTimer(5,printer)
t.start()

これは止めることができます t.cancel()


3
このコードにはcancelメソッドのバグがあると思います。これが呼び出されると、スレッドは1)実行されていないか、2)実行されています。1)では、関数の実行を待機しているため、キャンセルは正常に機能します。2)では現在実行中のため、キャンセルは現在の実行に影響を与えません。さらに、現在の実行はそれ自体を再スケジュールするため、将来の影響には影響しません。
リッチエピスコポ2016

1
このコードは、タイマーが終了するたびに新しいスレッドを作成します。これは、受け入れられた回答と比較して、途方もない無駄です。
エイドリアンW

上記の理由により、このソリューションは避けてください。毎回新しいスレッドが作成されます
Pynchia

17

Hans Thenの答えを少し改善するには、Timer関数をサブクラス化するだけです。以下は、「繰り返しタイマー」コード全体となり、すべて同じ引数を持つthreading.Timerのドロップイン置換として使用できます。

from threading import Timer

class RepeatTimer(Timer):
    def run(self):
        while not self.finished.wait(self.interval):
            self.function(*self.args, **self.kwargs)

使用例:

def dummyfn(msg="foo"):
    print(msg)

timer = RepeatTimer(1, dummyfn)
timer.start()
time.sleep(5)
timer.cancel()

次の出力が生成されます。

foo
foo
foo
foo

そして

timer = RepeatTimer(1, dummyfn, args=("bar",))
timer.start()
time.sleep(5)
timer.cancel()

作り出す

bar
bar
bar
bar

このアプローチでは、タイマースレッドを開始/キャンセル/開始/キャンセルできますか?
Paul Knopf

1
いいえ。このアプローチでは、通常のタイマーでできることは何でも可能ですが、通常のタイマーではできません。start / cancelは基礎となるスレッドに関連しているため、以前に.cancel()されたスレッドを.start()しようとすると、例外が発生しRuntimeError: threads can only be started onceます。
right2clicky 2018

本当にエレガントなソリューション!奇妙なことに、これを行うクラスが含まれていませんでした。
Roger Dahl、

このソリューションは非常に印象的ですが、Python3スレッドタイマーインターフェイスのドキュメントを単に読むだけでどのように設計されたかを理解するのに苦労しました。答えは、threading.pyモジュール自体に進むことによって実装を知ることに基づいているようです。
Adam.at.Epsilon

14

要求されたOPとしてタイマーを使用して正しい答えを提供するために、私はswapnil jariwalaの答えを改善します

from threading import Timer


class InfiniteTimer():
    """A Timer class that does not stop, unless you want it to."""

    def __init__(self, seconds, target):
        self._should_continue = False
        self.is_running = False
        self.seconds = seconds
        self.target = target
        self.thread = None

    def _handle_target(self):
        self.is_running = True
        self.target()
        self.is_running = False
        self._start_timer()

    def _start_timer(self):
        if self._should_continue: # Code could have been running when cancel was called.
            self.thread = Timer(self.seconds, self._handle_target)
            self.thread.start()

    def start(self):
        if not self._should_continue and not self.is_running:
            self._should_continue = True
            self._start_timer()
        else:
            print("Timer already started or running, please wait if you're restarting.")

    def cancel(self):
        if self.thread is not None:
            self._should_continue = False # Just in case thread is running and cancel fails.
            self.thread.cancel()
        else:
            print("Timer never started or failed to initialize.")


def tick():
    print('ipsem lorem')

# Example Usage
t = InfiniteTimer(0.5, tick)
t.start()

3

swapnil-jariwalaコードのコードをいくつか変更して、小さなコンソールクロックを作成しました。

from threading import Timer, Thread, Event
from datetime import datetime

class PT():

    def __init__(self, t, hFunction):
        self.t = t
        self.hFunction = hFunction
        self.thread = Timer(self.t, self.handle_function)

    def handle_function(self):
        self.hFunction()
        self.thread = Timer(self.t, self.handle_function)
        self.thread.start()

    def start(self):
        self.thread.start()

def printer():
    tempo = datetime.today()
    h,m,s = tempo.hour, tempo.minute, tempo.second
    print(f"{h}:{m}:{s}")


t = PT(1, printer)
t.start()

出力

>>> 11:39:11
11:39:12
11:39:13
11:39:14
11:39:15
11:39:16
...

tkinterグラフィックインターフェイスを備えたタイマー

このコードは、tkinterで小さなウィンドウに時計タイマーを配置します

from threading import Timer, Thread, Event
from datetime import datetime
import tkinter as tk

app = tk.Tk()
lab = tk.Label(app, text="Timer will start in a sec")
lab.pack()


class perpetualTimer():

    def __init__(self, t, hFunction):
        self.t = t
        self.hFunction = hFunction
        self.thread = Timer(self.t, self.handle_function)

    def handle_function(self):
        self.hFunction()
        self.thread = Timer(self.t, self.handle_function)
        self.thread.start()

    def start(self):
        self.thread.start()

    def cancel(self):
        self.thread.cancel()


def printer():
    tempo = datetime.today()
    clock = "{}:{}:{}".format(tempo.hour, tempo.minute, tempo.second)
    try:
        lab['text'] = clock
    except RuntimeError:
        exit()


t = perpetualTimer(1, printer)
t.start()
app.mainloop()

フラッシュカードゲームの例(一種)

from threading import Timer, Thread, Event
from datetime import datetime


class perpetualTimer():

    def __init__(self, t, hFunction):
        self.t = t
        self.hFunction = hFunction
        self.thread = Timer(self.t, self.handle_function)

    def handle_function(self):
        self.hFunction()
        self.thread = Timer(self.t, self.handle_function)
        self.thread.start()

    def start(self):
        self.thread.start()

    def cancel(self):
        self.thread.cancel()


x = datetime.today()
start = x.second


def printer():
    global questions, counter, start
    x = datetime.today()
    tempo = x.second
    if tempo - 3 > start:
        show_ans()
    #print("\n{}:{}:{}".format(tempo.hour, tempo.minute, tempo.second), end="")
    print()
    print("-" + questions[counter])
    counter += 1
    if counter == len(answers):
        counter = 0


def show_ans():
    global answers, c2
    print("It is {}".format(answers[c2]))
    c2 += 1
    if c2 == len(answers):
        c2 = 0


questions = ["What is the capital of Italy?",
             "What is the capital of France?",
             "What is the capital of England?",
             "What is the capital of Spain?"]

answers = "Rome", "Paris", "London", "Madrid"

counter = 0
c2 = 0
print("Get ready to answer")
t = perpetualTimer(3, printer)
t.start()

出力:

Get ready to answer
>>> 
-What is the capital of Italy?
It is Rome

-What is the capital of France?
It is Paris

-What is the capital of England?
...

hFunctionがブロックしている場合、これにより後続の開始時間にいくらかの遅延が追加されませんか?おそらく、handle_functionが最初にタイマーを開始してからhFunctionを呼び出すように、行を入れ替えることができますか?
口ひげ

2

私はプロジェクトのためにこれをしなければなりませんでした。私がやったことは、関数の別のスレッドを開始することでした

t = threading.Thread(target =heartbeat, args=(worker,))
t.start()

****ハートビートは私の機能、ワーカーは私の引数の1つです****

私のハートビート機能の内側:

def heartbeat(worker):

    while True:
        time.sleep(5)
        #all of my code

したがって、スレッドを開始すると、関数は5秒間繰り返し待機し、すべてのコードを実行して、それを無期限に実行します。プロセスを強制終了したい場合は、スレッドを強制終了してください。



1
from threading import Timer
def TaskManager():
    #do stuff
    t = Timer( 1, TaskManager )
    t.start()

TaskManager()

これは小さなサンプルです。実行方法を理解するのに役立ちます。関数taskManager()は最後に、それ自体への遅延関数呼び出しを作成します。

「dalay」変数を変更してみてください。違いがわかります。

from threading import Timer, _sleep

# ------------------------------------------
DATA = []
dalay = 0.25 # sec
counter = 0
allow_run = True
FIFO = True

def taskManager():

    global counter, DATA, delay, allow_run
    counter += 1

    if len(DATA) > 0:
        if FIFO:
            print("["+str(counter)+"] new data: ["+str(DATA.pop(0))+"]")
        else:
            print("["+str(counter)+"] new data: ["+str(DATA.pop())+"]")

    else:
        print("["+str(counter)+"] no data")

    if allow_run:
        #delayed method/function call to it self
        t = Timer( dalay, taskManager )
        t.start()

    else:
        print(" END task-manager: disabled")

# ------------------------------------------
def main():

    DATA.append("data from main(): 0")
    _sleep(2)
    DATA.append("data from main(): 1")
    _sleep(2)


# ------------------------------------------
print(" START task-manager:")
taskManager()

_sleep(2)
DATA.append("first data")

_sleep(2)
DATA.append("second data")

print(" START main():")
main()
print(" END main():")

_sleep(2)
DATA.append("last data")

allow_run = False

1
これが機能する理由についてもう少し詳しく教えてもらえますか?
minocha 2016年

あなたの例は少し混乱しました、最初のコードブロックはあなたが言う必要があるすべてでした。
Partack

1

私はright2clickyの答えが好きです。特に、スレッドを破棄する必要がなく、タイマーが作動するたびに新しいスレッドを作成する必要がないという点で。さらに、定期的に呼び出されるタイマーコールバックを持つクラスを作成するのは簡単なオーバーライドです。それが私の通常の使用例です。

class MyClass(RepeatTimer):
    def __init__(self, period):
        super().__init__(period, self.on_timer)

    def on_timer(self):
        print("Tick")


if __name__ == "__main__":
    mc = MyClass(1)
    mc.start()
    time.sleep(5)
    mc.cancel()

1

これは、クラスの代わりに関数を使用した代替実装です。上記の@Andrew Wilkinsに触発されました。

待機はスリープよりも正確なので(関数の実行時間を考慮に入れます):

import threading

PING_ON = threading.Event()

def ping():
  while not PING_ON.wait(1):
    print("my thread %s" % str(threading.current_thread().ident))

t = threading.Thread(target=ping)
t.start()

sleep(5)
PING_ON.set()

1

SingleTonクラスで別のソリューションを考え出しました。ここにメモリリークがあるかどうか教えてください。

import time,threading

class Singleton:
  __instance = None
  sleepTime = 1
  executeThread = False

  def __init__(self):
     if Singleton.__instance != None:
        raise Exception("This class is a singleton!")
     else:
        Singleton.__instance = self

  @staticmethod
  def getInstance():
     if Singleton.__instance == None:
        Singleton()
     return Singleton.__instance


  def startThread(self):
     self.executeThread = True
     self.threadNew = threading.Thread(target=self.foo_target)
     self.threadNew.start()
     print('doing other things...')


  def stopThread(self):
     print("Killing Thread ")
     self.executeThread = False
     self.threadNew.join()
     print(self.threadNew)


  def foo(self):
     print("Hello in " + str(self.sleepTime) + " seconds")


  def foo_target(self):
     while self.executeThread:
        self.foo()
        print(self.threadNew)
        time.sleep(self.sleepTime)

        if not self.executeThread:
           break


sClass = Singleton()
sClass.startThread()
time.sleep(5)
sClass.getInstance().stopThread()

sClass.getInstance().sleepTime = 2
sClass.startThread()
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.