0
私は関数をx秒ごとに呼び出す必要がありますが、手動で呼び出すオプションとこの場合はリセット時間を指定する必要があります。私はこのようなかなっている:今、このような私のコードを見てPython - Thread that I can pause and resume ::私は私をたくさん助けた何かを発見した :Pythonの一時停止スレッドは手動で行い、リセットする
import time
import threading
def printer():
print("do it in thread")
def do_sth(event):
while not event.is_set():
printer()
time.sleep(10)
event = threading.Event()
print("t - terminate, m - manual")
t = threading.Thread(target=do_sth, args=(event,))
t.daemon = True
t.start()
a = input()
if a == 't':
event.set()
elif a == 'm':
event.wait()
printer()
event.clear()
UPDATEを
import threading, time, sys
class ThreadClass(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.can_run = threading.Event()
self.thing_done = threading.Event()
self.thing_done.set()
self.can_run.set()
def run(self):
while True:
self.can_run.wait()
try:
self.thing_done.clear()
self.do_in_thread()
finally:
self.thing_done.set()
time.sleep(5)
def pause(self):
self.can_run.clear()
self.thing_done.wait()
def resume(self):
self.can_run.set()
def do_in_thread(self):
print("Thread...1")
time.sleep(2)
print("Thread...2")
time.sleep(2)
print("Thread...3")
def do_in_main():
print("Main...1")
time.sleep(2)
print("Main...2")
time.sleep(2)
print("Main...3")
if __name__ == '__main__':
t = ThreadClass()
t.daemon = True
t.start()
while True:
i = input()
if i == 'm':
t.pause()
do_in_main()
t.resume()
elif i == 't':
sys.exit()
# t.join()
は唯一の問題は、私が終了したときにということですは、スレッドが終了する前に仕事を終えるようにします。
を:あなたがいずれかを持っていますかそれに関する特定の質問? –
申し訳ありませんが、動作しないとは言いませんでした。私は関数プリンタを手動で呼び出す部分を意味します。このコードは正しくないので、何が間違っているのか教えていただけますか? – user2357858