-
青春有我
这可能是您正在寻找的正确片段:import threadingdef set_interval(func, sec): def func_wrapper(): set_interval(func, sec) func() t = threading.Timer(sec, func_wrapper) t.start() return t
-
qq_笑_17
这是您可以启动和停止的版本。它没有阻塞。由于没有添加执行时间错误,因此也没有毛刺(例如,对于音频间隔很短的长时间执行很重要)import time, threadingStartTime=time.time()def action() : print('action ! -> time : {:.1f}s'.format(time.time()-StartTime))class setInterval : def __init__(self,interval,action) : self.interval=interval self.action=action self.stopEvent=threading.Event() thread=threading.Thread(target=self.__setInterval) thread.start() def __setInterval(self) : nextTime=time.time()+self.interval while not self.stopEvent.wait(nextTime-time.time()) : nextTime+=self.interval self.action() def cancel(self) : self.stopEvent.set()# start action every 0.6sinter=setInterval(0.6,action)print('just after setInterval -> time : {:.1f}s'.format(time.time()-StartTime))# will stop interval in 5st=threading.Timer(5,inter.cancel)t.start()输出为:just after setInterval -> time : 0.0saction ! -> time : 0.6saction ! -> time : 1.2saction ! -> time : 1.8saction ! -> time : 2.4saction ! -> time : 3.0saction ! -> time : 3.6saction ! -> time : 4.2saction ! -> time : 4.8s
-
拉丁的传说
只要保持它的美观和简单即可。import threadingdef setInterval(func,time): e = threading.Event() while not e.wait(time): func()def foo(): print "hello"# usingsetInterval(foo,5)# output:hellohello...编辑:此代码是非阻塞的import threadingclass ThreadJob(threading.Thread): def __init__(self,callback,event,interval): '''runs the callback function after interval seconds :param callback: callback function to invoke :param event: external event for controlling the update operation :param interval: time in seconds after which are required to fire the callback :type callback: function :type interval: int ''' self.callback = callback self.event = event self.interval = interval super(ThreadJob,self).__init__() def run(self): while not self.event.wait(self.interval): self.callback()event = threading.Event()def foo(): print "hello"k = ThreadJob(foo,event,2)k.start()print "It is non-blocking"