小编典典

在Python中每x秒重复执行一个函数的最佳方法是什么?

python

我想永远每60秒重复执行一次Python中的函数(就像Objective C中的NSTimer一样)。该代码将作为守护程序运行,实际上就像使用cron每分钟调用python脚本一样,但是不需要用户设置。

在有关使用Python实现的cron的问题中,该解决方案似乎实际上只是将sleep()停留了x秒。我不需要这种高级功能,所以也许这样的事情会起作用

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

该代码是否存在任何可预见的问题?


阅读 836

收藏
2020-02-08

共2个答案

小编典典

使用sched模块,该模块实现了通用事件调度程序。

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()
2020-02-08
小编典典

只需将你的时间循环锁定到系统时钟即可。简单。

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