在没有 .after 或线程的情况下每 n 毫秒调用一个函数的计时器
timer that calls every n milliseconds a function without .after or threading
我需要一个每 n 毫秒调用一个函数的计时器。
这不应该在 endloss 循环中(虽然是真的)或类似的东西
import threading
def printit():
threading.Timer(5.0, printit).start()
print "Hello, World!"
或
def printit():
root.after(100,printit())
因为我有一个应该能够交互的 GUI。这样我就可以停止计时器了。
一些想法?
谢谢!
from threading import Timer
def hello():
print "hello, world"
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed`
您的问题明确表示不要使用 after
,但这正是您使用 tkinter 的方式(假设您的函数完成时间不超过几百毫秒)。例如:
def printit():
if not stopFlag:
root.after(100,printit)
...
def stop():
global stopFlag
stopFlag = False
...
printit()
上面的代码会导致每 100 毫秒调用一次 printit
,直到其他一些代码将 stopFlag
设置为 False
。
注意:如果 printit
花费超过 100 毫秒,这将不会很好地工作。如果该函数需要花费两倍的时间,那么您唯一的选择就是将该函数移到一个线程中,或者将它移到另一个进程中。如果 printit
花费 100 毫秒或更少,以上代码足以让您的 UI 保持响应。
我需要一个每 n 毫秒调用一个函数的计时器。 这不应该在 endloss 循环中(虽然是真的)或类似的东西
import threading
def printit():
threading.Timer(5.0, printit).start()
print "Hello, World!"
或
def printit():
root.after(100,printit())
因为我有一个应该能够交互的 GUI。这样我就可以停止计时器了。
一些想法? 谢谢!
from threading import Timer
def hello():
print "hello, world"
t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed`
您的问题明确表示不要使用 after
,但这正是您使用 tkinter 的方式(假设您的函数完成时间不超过几百毫秒)。例如:
def printit():
if not stopFlag:
root.after(100,printit)
...
def stop():
global stopFlag
stopFlag = False
...
printit()
上面的代码会导致每 100 毫秒调用一次 printit
,直到其他一些代码将 stopFlag
设置为 False
。
注意:如果 printit
花费超过 100 毫秒,这将不会很好地工作。如果该函数需要花费两倍的时间,那么您唯一的选择就是将该函数移到一个线程中,或者将它移到另一个进程中。如果 printit
花费 100 毫秒或更少,以上代码足以让您的 UI 保持响应。