0
我需要每隔x秒調用一次函數,但可以選擇手動調用它,在這種情況下需要重置時間。我也有東西是這樣的: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()
更新: 我發現的東西,對我幫助很大:Python - Thread that I can pause and resume 現在我的代碼看起來是這樣的:
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()
唯一的問題是,當我結束,希望線程在退出前完成工作。
由於SO不是代碼編寫的服務:你有什麼具體的問題呢? –
對不起,我沒有提到它不起作用。我的意思是我手動調用功能打印機的部分。這段代碼不正確,所以你能告訴我我做錯了什麼? – user2357858