我希望永远每隔60秒重复执行一次Python语言中的函数(就像Objective C中的NSTimer或JS中的setTimeout一样)。这段代码将作为守护进程运行,实际上就像使用cron每分钟调用一次python脚本,但不需要用户进行设置。
在this question about a cron implemented in Python中,解决方案似乎只需sleep() x秒即可。我不需要这么高级的功能,所以这样的功能可能会起作用。
while True:
# Code executed here
time.sleep(60)
这段代码有没有什么可预见的问题?
发布于 2009-01-23 21:09:33
如果您的程序还没有事件循环,那么可以使用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()
如果您已经在使用asyncio
、trio
、tkinter
、PyQt5
、gobject
、kivy
等事件循环库,那么只需使用现有事件循环库的方法来调度任务即可。
发布于 2014-08-12 04:25:25
将您的时间循环锁定到系统时钟,如下所示:
import time
starttime = time.time()
while True:
print("tick")
time.sleep(60.0 - ((time.time() - starttime) % 60.0))
发布于 2009-01-23 21:14:06
您可能需要考虑Twisted,它是一个实现Reactor Pattern的Python网络库。
from twisted.internet import task, 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()
虽然"while True: sleep(60)“可能会起作用,但Twisted可能已经实现了您最终需要的许多特性(守护进程、日志记录或波本斯指出的异常处理),并且可能是一个更健壮的解决方案
https://stackoverflow.com/questions/474528
复制相似问题