PDA

View Full Version : Timer signals in non GUI application



mcosta
16th September 2010, 17:58
Hi,

first of all, sorry for my bad English.
Now the question.

I've written a class inherited from QThread


// DataSender.cpp

DataSender::DataSender(QObject *parent) : QThread(parent)
{
this->m_sendTimer.setInterval (0);

connect (&m_sendTimer, SIGNAL(timeout()), this, SLOT(sendData()));
}

void DataSender::setSendInterval (int msec)
{
this->m_sendTimer.setInterval (msec);
}

void DataSender::run ()
{
bool ans = true;

qDebug ("%s Started", qPrintable(this->objectName ()));

if (ans && this->m_sendTimer.interval () > 0) {
this->m_sendTimer.start ();
qDebug ("%s: Timer Started", qPrintable(this->objectName ()));
}

if (ans) {
this->exec ();
}

this->m_sendTimer.stop ();

qDebug ("%s Stopped", qPrintable(this->objectName ()));
}


This class is in a library.

When I use it in a GUI Application it works


void MainWindow::startSenders ()
{
DataSender* s = 0;
for (int i = 0; i < DATA_TYPE_SIZE; ++i) {
s = &this->m_senders[i];
s->setSendInterval (10000);
s->sender->start ();
}
qDebug ("Senders Started");
}


but when I use it in a non-GUI application


// Main.cpp
...
DataSender* senders[2];

senders[0] = new DataSender;
senders[0]->setSendInterval(1000);

senders[1] = new DataSender;
senders[1]->setSendInterval(5000);

qDebug ("RUNNING...");

for (int i = 0; i < 2; ++i) {
senders[i]->start ();
}
result = app.exec ();
...

the slot connected to the timeout() signal of timer is never called.
The debug messages in DataSender.cpp at line 19 and 23 are printed; that means the thread is correctly started.

Any suggestion?

wysota
16th September 2010, 22:25
And you don't get warnings at the console not to start timers from threads different than the ones they were created in? In general I'm more suprised it is working for you when the application has a GUI than that it doesn't work when there is no GUI.

mcosta
17th September 2010, 11:36
Hi wysota, thanks for the answer.

I modified the code in way to create QTimer in QThread::run() and it works.

The question is:
Why the GUI version works? (The warning messages was shown both in GUI and non-GUI version)

wysota
17th September 2010, 11:52
The question is:
Why the GUI version works?
No idea. Maybe there are different safe guards in QCoreApplication and QApplication or maybe it's just pure coincidence.