0

I need a timer that calls a function every n milliseconds. This should not be in a endloss loop (while true) or something like that

import threading

def printit():
   threading.Timer(5.0, printit).start()
   print "Hello, World!"

Or

def printit():
    root.after(100,printit())

As I have a GUI that should be able to interact. So that I can stop the timer.

Some ideas? Thanks!

user47091
  • 523
  • 2
  • 6
  • 16
  • Take a look at this link you should find help there http://stackoverflow.com/questions/9812344/cancellable-threading-timer-in-python – Nobi Jun 12 '15 at 10:37
  • 1
    why "without .after"? That's exactly what you should use in tkinter. With `after`, you can interact during the periods when the function isn't running, and you can certainly stop the loop at any time. – Bryan Oakley Jun 12 '15 at 10:40
  • You are right. But the function that the timer shall call is a more or less real-time data plot function. So the timer should call it really fast. So there is no time for the user to interrupt it. Is there another way to stop a function during the process? – user47091 Jun 12 '15 at 10:59
  • How long does the "real-time data plot function" take? Does it run in just a few hundred milliseconds or less? – Bryan Oakley Jun 12 '15 at 11:00

2 Answers2

3

Your question explictly says not to use after, but that's exactly how you do it with tkinter (assuming your function doesn't take more than a couple hundred ms to complete). For example:

def printit():
    if not stopFlag:
        root.after(100,printit)
...
def stop():
    global stopFlag
    stopFlag = False
...
printit()

The above will cause printit to be called every 100ms until some other piece of code sets stopFlag to False.

Note: this will not work very well if printit takes more than 100ms. If the function takes two much time, your only choices are to move the function into a thread, or move it to another process. If printit takes 100ms or less, the above code is sufficient to keep your UI responsive.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
0

From Python Documentation

from threading import Timer
def hello():
    print "hello, world"

t = Timer(30.0, hello)
t.start() # after 30 seconds, "hello, world" will be printed`
Vaulstein
  • 20,055
  • 8
  • 52
  • 73