项目中需要使用定时器,每次都使用构造器函数调用:
timer = threading.Timer(timerFlag, upload_position)
timer.start()
打印线程后发现,每次都会创建一个新的子线程,虽然活跃的线程只有一个,但是也是种资源浪费:
print("threading active = {} \n \n".format(threading.enumerate()))
#打印
threading active = [<_mainthread stopped>, ]
threading active = [<_mainthread stopped>, ]
threading active = [<_mainthread stopped>, ]
threading active = [<_mainthread stopped>, ]
threading active = [<_mainthread stopped>, ]
threading active = [<_mainthread stopped>, ]
threading active = [<_mainthread stopped>, ]
阅读源码和文档
class Timer(Thread):
"""Call a function after a specified number of seconds:
t = Timer(30.0, f, args=None, kwargs=None)
t.start()<