在上位机软件开发过程中,你难免不得等待下位机上传的数据,当没有信息上传,超时机制就能保证上位机不会卡死。那么在实际使用中,一般我们怎么添加呢?
Qt中自带QTimer类,如果你只是简单的做个定时器,直接到主线程GUI线程中进行定时炒作即可,但是经常会卡主界面,那么我们需要怎么在子线程中进行定时器开启呢?
timeoutmannager.h
- /*********************************************************************************
- *Author:zhouFuLiang
- *Date: 2023-09-14 20:50
- *Description: 超时机制功能
- **********************************************************************************/
- #ifndef TIMEOUTMANAGER_H
- #define TIMEOUTMANAGER_H
-
- #include
- #include
- #include
-
-
- #define Max_Count 2
-
- class TimeoutManager : public QObject
- {
- Q_OBJECT
- public:
- explicit TimeoutManager(QObject *parent = 0);
-
- private:
- void initConnect();
- signals:
- void commandException(int, int); //命令执行超时
- public slots:
- void timerOutSlot();
- void threadStartRun();
- void threadStopRun();
- void destoryResource();
- void onSetCurrentCommand(int cm, int cpr);
-
- private:
- QThread *m_pThread;
- QTimer *m_pTimer;
- int m_nCount;
- int m_currProcess;
- int m_currCommand;
- };
-
- #endif // TIMEOUTMANAGER_H
timeoutmannager.cpp
- #include "timeoutmanager.h"
- #include
-
- TimeoutManager::TimeoutManager(QObject *parent) : QObject(parent)
- ,m_pThread(nullptr)
- ,m_nCount(0)
- ,m_currCommand(-1)
- ,m_currProcess(-1)
- {
- m_pThread = new QThread;
- m_pTimer = new QTimer;
-
- moveToThread(m_pThread);
- m_pTimer->moveToThread(m_pThread);
- m_pThread->start();
-
- initConnect();
- }
-
- void TimeoutManager::threadStartRun()
- {
- m_pTimer->start(1000);
- }
-
- void TimeoutManager::threadStopRun()
- {
- m_pTimer->stop();
- m_pTimer->deleteLater();
- }
-
- void TimeoutManager::destoryResource()
- {
- m_pThread->quit();
- m_pThread->wait();
- }
-
- void TimeoutManager::onSetCurrentCommand(int cm, int cpr)
- {
- this->m_currCommand = cm;
- this->m_currProcess = cpr;
- }
-
-
- void TimeoutManager::initConnect()
- {
- connect(qApp, &QApplication::aboutToQuit, this, &TimeoutManager::destoryResource, Qt::DirectConnection);
- connect(m_pTimer, &QTimer::timeout, this, &TimeoutManager::timerOutSlot, Qt::DirectConnection);
- connect(m_pThread, &QThread::started, this, &TimeoutManager::threadStartRun, Qt::DirectConnection);
- connect(m_pThread, &QThread::finished, this, &TimeoutManager::threadStopRun, Qt::DirectConnection);
- }
-
- void TimeoutManager::timerOutSlot()
- {
- if(-1 == m_currCommand)
- return;
- m_nCount++;
- if (m_nCount > Max_Count) {
- m_nCount = 0;
- emit commandException(m_currCommand,m_currProcess);
- qDebug() << "trigger signal command: " <<QString("0x%1").arg(m_currCommand ,2, 16, QChar('0')) << " process: " << QString("0x%1").arg(m_currProcess ,2, 16, QChar('0'));
- m_currCommand = -1;
- m_currProcess = -1;
- }
- }
main函数中
connect 这个onSetCurrentCommand 槽函数,在启动时候,进行触发
connect这个commandException信号,那么超时后就会触发