我想永远每60秒在Python中重复执行一个函数(就像目标C中的NSTimer一样).这段代码将作为守护进程运行,实际上就像使用cron每分钟调用python脚本一样,但不需要用户设置.
在这个关于用Python实现的cron的问题中,解决方案似乎实际上只是sleep() x秒.我不需要这样的高级功能,所以也许这样的东西可行
while True:
# Code executed here
time.sleep(60)
Run Code Online (Sandbox Code Playgroud)
这段代码有可预见的问题吗?
有没有办法,例如,Hello World!每n秒打印一次?例如,程序将通过我拥有的任何代码,然后一旦它有5秒(有time.sleep())它将执行该代码.我会使用它来更新文件,而不是打印Hello World.
例如:
startrepeat("print('Hello World')", .01) # Repeats print('Hello World') ever .01 seconds
for i in range(5):
print(i)
>> Hello World!
>> 0
>> 1
>> 2
>> Hello World!
>> 3
>> Hello World!
>> 4
Run Code Online (Sandbox Code Playgroud) 我试图弄清楚如何制作一个在python中取消的setInterval而不需要创建一个完整的新类,我想出了如何但现在我想知道是否有更好的方法来做到这一点.
下面的代码似乎工作正常,但我没有彻底测试它.
import threading
def setInterval(func, sec):
def inner():
while function.isAlive():
func()
time.sleep(sec)
function = type("setInterval", (), {}) # not really a function I guess
function.isAlive = lambda: function.vars["isAlive"]
function.vars = {"isAlive": True}
function.cancel = lambda: function.vars.update({"isAlive": False})
thread = threading.Timer(sec, inner)
thread.setDaemon(True)
thread.start()
return function
interval = setInterval(lambda: print("Hello, World"), 60) # will print Hello, World every 60 seconds
# 3 minutes later
interval.cancel() # it will stop printing Hello, World
Run Code Online (Sandbox Code Playgroud)
有没有办法在不创建继承threading.Thread或使用的专用类的情况下执行上述操作type("setInterval", (), {}) …