# 什么是在Python中每隔x秒重复执行一次函数的最好方法？

``while True: # Code executed here time.sleep(60)` `

### 11 Solutions collect form web for “什么是在Python中每隔x秒重复执行一次函数的最好方法？”

` `import sched, time s = sched.scheduler(time.time, time.sleep) def do_something(sc): print "Doing stuff..." # do your stuff s.enter(60, 1, do_something, (sc,)) s.enter(60, 1, do_something, (s,)) s.run()` `

` `import time starttime=time.time() while True: print "tick" time.sleep(60.0 - ((time.time() - starttime) % 60.0))` `

` `from twisted.internet import task from twisted.internet import reactor timeout = 60.0 # Sixty seconds def doWork(): #do work here pass l = task.LoopingCall(doWork) l.start(timeout) # call every sixty seconds reactor.run()` `

` `import time def executeSomething(): #code here time.sleep(60) while True: executeSomething()` `

` `from threading import Timer class RepeatedTimer(object): def __init__(self, interval, function, *args, **kwargs): self._timer = None self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.is_running = False self.start() def _run(self): self.is_running = False self.start() self.function(*self.args, **self.kwargs) def start(self): if not self.is_running: self._timer = Timer(self.interval, self._run) self._timer.start() self.is_running = True def stop(self): self._timer.cancel() self.is_running = False` `

` `from time import sleep def hello(name): print "Hello %s!" % name print "starting..." rt = RepeatedTimer(1, hello, "World") # it auto-starts, no need of rt.start() try: sleep(5) # your long-running job goes here... finally: rt.stop() # better in a try/finally block to make sure the program ends!` `

• 只有标准库，没有外部依赖
• 即使定时器已经开始/停止， `start()``stop()`也可以安全地多次调用
• 函数被调用可以有位置和命名参数
• 您可以随时更改`interval` ，下次运行后生效。 同样的`args``kwargs`甚至`function`

` `class RepeatedTimer(object): def __init__(self, interval, function, *args, **kwargs): self._timer = None self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.is_running = False self.next_call = time.time() self.start() def _run(self): self.is_running = False self.start() self.function(*self.args, **self.kwargs) def start(self): if not self.is_running: self.next_call += self.interval self._timer = threading.Timer(self.next_call - time.time(), self._run) self._timer.start() self.is_running = True def stop(self): self._timer.cancel() self.is_running = False` `

` `import cronus.beat as beat beat.set_rate(2) # 2 Hz while beat.true(): # do some time consuming work here beat.sleep() # total loop duration would be 0.5 sec` `

` `import time t=time.time() while True: if time.time()-t>10: #run your task here t=time.time()` `

` `import math import time import random TICK = 60 # one minute tick size TICK_TIMING = 59 # execute on 59th second of the tick TICK_MINIMUM = 30 # minimum catch up tick size when lagging def set_timing(): now = time.time() elapsed = now - info['begin'] minutes = math.floor(elapsed/TICK) tick_elapsed = now - info['completion_time'] if (info['tick']+1) > minutes: wait = max(0,(TICK_TIMING-(time.time() % TICK))) print ('standard wait: %.2f' % wait) time.sleep(wait) elif tick_elapsed < TICK_MINIMUM: wait = TICK_MINIMUM-tick_elapsed print ('minimum wait: %.2f' % wait) time.sleep(wait) else: print ('skip set_timing(); no wait') drift = ((time.time() - info['begin']) - info['tick']*TICK - TICK_TIMING + info['begin']%TICK) print ('drift: %.6f' % drift) info['tick'] = 0 info['begin'] = time.time() info['completion_time'] = info['begin'] - TICK while 1: set_timing() print('hello world') #random real world event time.sleep(random.random()*TICK_MINIMUM) info['tick'] += 1 info['completion_time'] = time.time()` `

` `60,60,62,58,60,60,120,30,30,60,60,60,60,60...etc.` `

` `import datetime import glib import logger def get_local_time(): current_time = datetime.datetime.now().strftime("%H:%M") logger.info("get_local_time(): %s",current_time) return str(current_time) def display_local_time(): logger.info("Current time is: %s", get_local_time()) # call every minute glib.timeout_add(60*1000, display_local_time)` `
• 我如何解决在for循环中声明一个未使用的variables？
• python 3.5：TypeError：需要类似字节的对象，而不是写入文件时的“str”
• Python中的string相似性度量
• Python中的==和`is`是否有区别？
• 将字典附加到字典？
• 有效地检查该string是否由Python中的一个字符组成
• Python vs Groovy与Ruby？ （根据问题列出的标准）
• Python属性如何工作？
• python中的hexstring到字节数组
• 如何将string数组转换为numpy中的浮点数组？
• Django使用contains来过滤多对多