PyQt Quickie: QTimer

QTimer is a fairly simple class: you use it when you want something to happen "in a while" or "every once in a while".

The first case is something like this:

# call f() in 3 seconds
QTimer.singleShot(3000, f)

The second is this:

# Create a QTimer
timer = QTimer()
# Connect it to f
timer.timeout.connect(f)
# Call f() every 5 seconds
timer.start(5000)

Simple, right? Well, yes, but it has some tricks.

  1. You have to keep a reference to``timer``

    If you don't, it willget garbage-collected, and f() will never be called.

  2. It may not call f() in 5 seconds.

    It will call f() more or less 5 seconds after you enter the event loop. That may not be quickly after you start the timer at all!

  3. You may get overlapping calls.

    If f() takes long to finish and re-enters the event loop (for example, by calling processEvents) maybe the timer will timeout and call it again before it's finished. That's almost never a good thing.

So, you can do this:

def f():
    try:
        # Do things
    finally:
        QTimer.singleShot(5000, f)

f()

What that snippet does, is, calls f() only once. But f itself schedules itself to run in 5 seconds. Since it does it in a finally, it will do so even if things break.

That means no overlapping calls. It also means it won't be called every 5 seconds, but 5 seconds plus whatever f takes to run. Also, no need to keep any reference to a QTimer.

Final tip: You can also use QTimer to do something "as soon as you are in the event loop"

QTimer.singleShot(0, f)

Hope it was useful!

Comments

Comments powered by Disqus