[英]python timer thread shutdown
我正在尝试创建一个计时器工作线程,该线程可以随时退出。 python有一个内置计时器,其回调函数仅称为ONCE ?! 我不知道为什么将其称为计时器。
然后我必须在工作线程中入睡,这是一个坏主意。 timerThread.cancel()无法关闭工作线程。 如果我使用事件退出工作线程,则工作线程只能在唤醒后退出。
我期望有一个计时器工作线程,该线程可以随时退出。 而且我不希望工作线程被阻塞。
有一些方法可以实现它吗?
def Show():
while 1:
time.sleep(10)
print("Nice!")
if __name__ == '__main__':
timerThread = threading.Timer(1,Show)
timerThread.start()
while 1:
input = str(sys.stdin.readline())
if input == 'EXIT\n':
timerThread.cancel()
break;
就您而言,python中的Timer对象[1]仅运行一次,并在一段时间后执行一个函数。 但是,该函数可以启动新的Timer对象。 下面是此实现的示例。
timerThread = None
def timesUp():
global timerThread
print('Nice!')
timerThread = Timer(10, timesUp)
timerThread.start()
def main():
global timerThread
timerThread = Timer(10, timesUp)
timerThread.start()
while 1:
input = str(sys.stdin.readline())
if input == 'EXIT\n':
timerThread.cancel()
break;
总体而言,由于python中的GIL [2]问题,您将无法正确处理线程,因为一次只能有1个线程访问解释器。 这就是为什么python中的许多框架都是单线程异步框架(例如gevent [3],tornado [4])的原因。 他们不使用线程,而是在IOLoop(事件,epoll)上侦听,并协作将操作流传递给其他等待的协程。
[1] -https://docs.python.org/2/library/threading.html#timer-objects
您可以使用此类来解决您的问题。
import time
from threading import Thread
class Timer(Thread):
def __init__(self, seconds, callback, *args, **kwargs):
Thread.__init__(self)
assert callable(callback)
self.__callback = callback
self.__seconds = seconds
self.__args = args
self.__kwargs = kwargs
self.running = False
def run(self):
self.running = True
while self.running:
Thread(target=self.__callback, args=self.__args, kwargs=self.__kwargs).start()
time.sleep(self.__seconds)
def stop(self):
self.running = False
要调用此函数,请使用
def Test(spam,eggs=10):
print spam, eggs
timerFunction = Timer(1,Test,10,eggs=99) # The number 1 is the time in seconds
timerFunction.start()
要停止执行,请使用:
timerFunction.stop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.