我正在尝试创建一个计时器工作线程,它可以在任何时候退出。python有一个内置计时器,它的回调函数只调用一次?!我不知道为什么叫计时器。
然后我就得在工作线程里睡一觉,这是个坏主意。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;
发布于 2015-07-16 21:05:20
就您的观点而言,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问题,您将遇到线程正确处理的问题,因为一次只有一个线程可以访问解释器。这就是为什么python中的很多框架都是单线程的异步框架(例如gevent 3,Tor非议4)。它们没有使用线程,而是侦听IOLoop (eventlets,epoll),并协作地将操作流生成给其他等待的协同器。
1- https://docs.python.org/2/library/threading.html#timer-objects
发布于 2016-05-11 13:37:33
你可以用这个类来解决你的问题。
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()
https://stackoverflow.com/questions/31464270
复制相似问题