Qt 多线程开启定时任务

项目场景:

多线程执行一些耗时操作,并且需要固定时间去轮询。


代码:

#include 
#include 
#include 


class pollingManager : public QObject {
    Q_OBJECT

  public:
    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();
}

你可能感兴趣的:(qt,c++)