C++ (Qt)class DbWatcher : public QThread{ Q_OBJECTpublic: explicit DbWatcher(); explicit DbWatcher( int interval, QSqlDatabase db ); int interval() const; void setInterval( int val ); bool isConnected() const; QSqlDatabase connection() const; void setConnection( QSqlDatabase db ); signals: void connected(); void disconnected(); protected slots: void reconnect(); protected: virtual void run(); int m_interval; QSqlDatabase m_db; QTimer *m_timer; bool m_connOk; mutable QMutex m_mutex;};
C++ (Qt)DbWatcher::DbWatcher() : QThread( 0 ), m_interval( 0 ), m_db(), m_timer( 0 ), m_connOk( false ){ moveToThread( this );} DbWatcher::DbWatcher( int interval, QSqlDatabase db ) : QThread( 0 ), m_interval( interval ), m_db( db ), m_timer( 0 ), m_connOk( false ){ moveToThread( this );} int DbWatcher::interval() const{ QMutexLocker lock( &m_mutex ); return m_interval;} void DbWatcher::setInterval( int val ){ QMutexLocker lock( &m_mutex ); m_interval = val;} bool DbWatcher::isConnected() const{ QMutexLocker lock( &m_mutex ); return m_db.isOpen() && m_db.exec( "SELECT TRUE" ).isActive();} QSqlDatabase DbWatcher::connection() const{ QMutexLocker lock( &m_mutex ); return m_db;} void DbWatcher::setConnection( QSqlDatabase db ){ QMutexLocker lock( &m_mutex ); m_db = db;} void DbWatcher::reconnect(){ Q_ASSERT( m_timer ); if( isConnected() ) return; m_timer->stop(); if( m_connOk ) { m_connOk = false; emit disconnected(); } m_db.open(); if( isConnected() ) { m_connOk = true; emit connected(); } m_timer->start();} void DbWatcher::run(){ m_timer = new QTimer; connect( m_timer, SIGNAL(timeout()), SLOT(reconnect()) ); m_timer->setSingleShot( false ); m_timer->setInterval( m_interval * 1000 ); m_timer->start(); QMetaObject::invokeMethod( this, "reconnect", Qt::QueuedConnection ); exec(); m_timer->stop(); delete m_timer;}