简体   繁体   中英

Run Qt program in while loop

I'm running a C++ program, build with Qt, that never can stop.
The program always fetches data from database and if there is a result sends an SMS.

I'm able to connect to database, but after some hours (+/- 10), it doesn't work anymore.

I don't know if the problem is because I lose connection with database or because my computer goes standby...

I'm not able in Qt to see database status: db.open() always returns true when tested inside while loop.

QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("");
db.setPort();
db.setDatabaseName("");
db.setUserName("");
db.setPassword(""); 
if (db.open())
{
    while (true)
    {
        // MySQL Request
        // If data -> send SMS
    }
}

There's always the possibility to loose a DB connection for whatever reason. You just can't rely on it. You have to check your connection inside the loop and implement some kind of re-connection scheme if the connection gets lost. As far as I know Qt doesn't do that for you.

Qt provides an event driven framework; events occur and the program reacts to those events.

When you have a never ending loop, events are queued, waiting until they can be processed. In your case, this is never going to happen, so the queue of events will just keep increasing, taking up resources such as memory.

There are two possible ways of solving this. The first is to call QApplication::processEvents every now and again in your loop.

However, the better method would be to remove the while(true) and instead use a QTimer which will periodically call a function to process any available data.

Assuming you have a class, derived from QObject, here's skeleton code using QObject's own timer

class MyObject : public QObject
{
    Q_OBJECT

public:
    MyObject(QObject *parent = 0);

protected:
    // this will be called periodically from the timer
    void timerEvent(QTimerEvent *event);

private:
    m_timerId = 0; // C++ 11 initialisation
};

MyObject::MyObject(QObject *parent)
    : QObject(parent)
{
    m_timerId = startTimer(50);     // 50-millisecond timer
}

void MyObject::timerEvent(QTimerEvent *event)
{
    if(event->timerId() == m_timerId)
    {
        // MySQL Request
        // If data -> send SMS
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM