使用可重入锁实现一个定时任务,要求正常情况下每十秒执行一次,一旦条件修改则重新开始计时,很简单的一个小程序
import threading
import time
class Test:
def __init__(self):
self.ca = 10 # 计时器
self.lock = threading.RLock()
def change_ca(self):
with self.lock:
print("修改变量")
self.ca = 20
def thread_get_ca(self):
while True:
time.sleep(1)
with self.lock:
print(self.ca)
self.ca -= 1
def t1(self):
t1 = threading.Thread(name="t1", target=self.thread_get_ca, daemon=True)
t1.start()
if __name__ == '__main__':
test = Test()
test.t1()
time.sleep(3)
test.change_ca()
time.sleep(20)