Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QTimer timeout processing when Qt main event queue is blocked

Tags:

events

timer

qt

What happens if I start a QTimer firing at regular intervals but the slot reacting to the timeout signal blocks the main loop for longer than another timer interval. Will the timout signals then be stacked on the Qt main event loop and processed one after another as soon as the event loop runs again?

If yes, what happens if multiple timeout events are stacked on the event queue but the timer is deactivated before they can be processed?

like image 452
user1709708 Avatar asked Jun 25 '15 16:06

user1709708


1 Answers

If QTimer object and the signal receiver belong to one thread, no queuing happens. timeout() signal will not (and cannot) be sent again until control flow goes to the event loop, and that won't happen until the slot is completely executed (unless QApplication::processEvents is called in the slot, which can turn this into a mess). But if your slot was being executed longer than the timer's interval, timeout() will be sent once the event loop is free, so your slot will be immedately called again. But QTimer will not send two timeout() signals closer than its interval.

If QTimer is in another thread, and that thread is not busy with something else, it will send timeout() signals regularly regardless of how well slot in another thread goes. This is where Qt's signal-slot system comes in. And it will queue emitted signals. If your slot is slow, it will call it multiple times without delay. If you stop the timer, it won't undo already sent signals and the slot may be called multiple times after it. Additionally, if you stop the timer, there is always a possibility that another signal is being sent just in this moment and your slot will be called once again.

If you want strict intervals between slot invocations regardless of the slot's executing time, you should use single-shot timers. At the end of your slot, start a single-shot timer. When it's timed out, it will invoke your slot and deactivate, so you can start it again at the end of the slot.

If your program's logic depends on the timer's state, you should check that the timer is active at the start of your slot. It's not guaranteed that the timer is active when the slot is being executed.

like image 81
Pavel Strakhov Avatar answered Sep 26 '22 03:09

Pavel Strakhov