项目场景:
多线程执行一些耗时操作,并且需要固定时间去轮询。
代码:
#include <QThread> #include <QTimer> #include <QtCore/QMutex>class pollingManager : public QObject {Q_OBJECTpublic:static pollingManager*getInstance() {if ( !instance ) {instance = new pollingManager();}return instance;}void startTimerThread();signals:void timeout( void );slots:void timeoutHandle( void );private:pollingManager() {}~pollingManager() {}static pollingManager*instance;class pollingTimerThread : public QThread {public:void run() override;}; };#endif // A7TIMERPOLLDEVICE_H.cpp#define POLLING_TIMER 600 pollingManager *pollingManager ::instance = nullptr; void pollingManager ::startTimerThread() {qDebug( "startA7TimerThread" );pollingTimerThread*thread = new A7TimerThread();thread->setObjectName( "pollingThread" );thread->start(); }void pollingManager ::pollingTimerThread::run() {QTimer timer;timer.setInterval( POLLING_TIMER);connect( &timer, &QTimer::timeout, []() {timeoutHandle();} );timer.start();exec(); }