PDA

View Full Version : right way to use a QTimer on a console application.



weaver4
14th February 2012, 20:09
I have a console application that looks for a device on the network and gets data from it. It will either get the data within a few seconds or it get stuck in trying to receive data.

So I wanted to set up a Qtimer that would preform a quit after 10 seconds. Here is my code but it does not seem to work.


int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

QTimer::singleShot(10000, &a, SLOT(quit()));

// either will return within 3 seconds or get stuck trying to do a read.
LLDP::Execute();

return a.exec();
}


It is pretty much exactly what is in the singleShot documentation. My code is where the "..." are.


#include <QApplication>
#include <QTimer>

int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QTimer::singleShot(600000, &app, SLOT(quit()));
...
return app.exec();
}


What am I doing wrong and what is the correct way?

wysota
14th February 2012, 22:21
Please note that if your Execute() call "gets stuck", a.exec() never has a chance to execute hence your timer will not work. Timer alone can't solve your problem. You'd have to run your Execute() code in external thread while the main thread processes events allowing the timer to fire.

weaver4
15th February 2012, 14:20
Thanks, that did it.

Did not realize that the Timer would not work unless a.exec() was executed.