Is it safe to stop Qt’s timer in it’s “timeout” signal/slot function?
Can’t seem to find any information in Qt documentation about the QTimer.
I have created a timer that is periodically sending a “keep alive” messages to the server.
I want this timer to be stopped if there is some kind of error while sending my message.
private:
QTimer* mpKeepAliveTimer;
Timer is initialized like this:
mpKeepAliveTimer = new QTimer(/* this */);
QObject::connect(mpKeepAliveTimer, SIGNAL(timeout()), this, SLOT(OnKeepAlive()));
mpKeepAliveTimer->start(KEEP_ALIVE_PERIOD);
Stopped like this:
if (mpKeepAliveTimer != NULL) // <-- Edited
{
if (mpKeepAliveTimer->isActive() == true)
mpKeepAliveTimer->stop();
delete mpKeepAliveTimer;
mpKeepAliveTimer = NULL;
}
Timeout function looks like this:
void Classname::OnKeepAlive()
{
if (isErrorFound == true)
mpKeepAliveTimer->stop(); // <---- IS THIS SAFE?
}
Thanks.
As long as you are not explicitly using Queued Connections, this is safe.
This is because the
emit timeout()function will not return until all the slots it’s connected to were processed.If you were however using Queued Connections, it could in theory happen that there are still unprocessed timeout events in the Event Queue, so to make it hyper-safe you could use the following:
Note that the condition in your stop function should be
!= NULLinstead of== NULL. You can also write that function as follows, however:As already suggested in the comments, QTimer will stop itself in its destructor.