最准确的计时器Qt C ++ [英] The most accurate timer qt C++

查看:769
本文介绍了最准确的计时器Qt C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用QTimer定期将"Ping"数据包发送到服务器(MQTT客户端).但是它的计时器并不是绝对准确的.工作一段时间后,它会出现一些延迟并且服务器断开连接. 我尝试使用其他Qt :: TimerType,但这无济于事. 我需要最准确的计时器.你有什么主意吗?

I use QTimer to send periodically 'Ping' packet to the server (MQTT client). But it timer is not absolutely accurate. After some time of working it has some delay and server broken connection. I try to use different Qt::TimerType, but it does not help. I need the most accurate timer. Do you have any ideas?

谢谢!

我做了这样的事情:

tthread.h

class TThread : public QThread
{
    Q_OBJECT

    void run();

public:
    explicit TThread(QObject *parent = 0);

signals:

private slots:
    void timerOut();
};

tthread.cpp

TThread::TThread(QObject *parent) : QThread(parent)
{

}

void TThread::run()
{
    QTimer timer;
    connect(&timer, SIGNAL(timeout()), this, SLOT(timerOut()), Qt::DirectConnection);
    timer.start(1000);
    timer.moveToThread(this);
    exec();
}

void TThread::timerOut()
{
    QTime time = QTime();
    qDebug() << time.currentTime().toString();
}

main.cpp

TThread thread;
thread.start();
thread.setPriority(QThread::HighPriority);

推荐答案

在单独的QThread上运行QTimer,它不会执行其他任何操作. 如果您在一个已经很繁忙的线程上运行计时器,则超时事件可能不会按时出现或根本没有出现.

Run a QTimer on a separate QThread which doesn't do anything else. If you're running the timer on an already busy thread the timeout events may not come on time or not at all.

进行工人培训,例如"PingPacketWorker",实现执行ping操作的插槽. 制作一个QThread. 连接您的QTimer和PingPacketWorker信号/插槽. 启动计时器. 调用PingPacketWorker和QTimer上的moveToThread,由于moveToThread,计时器应重新启动,请注意,您只能在所有者线程上启动/停止它!

Make a worker class e.g. "PingPacketWorker", implement a slot that does pinging. Make a QThread. Connect your QTimer and PingPacketWorker signal/slots. Start the timer. Call moveToThread on the PingPacketWorker and the QTimer, the timer should restart because of moveToThread, note you can only start / stop it on the owner thread!

由于您要求最准确的"解决方案,因此您还可以提高QThread的优先级...

You could also increase your QThread's priority since you asked for "the most accurate" solution ...

更新:

还要设置QTimer :: setTimerType(Qt :: PreciseTimer)

Also, set QTimer::setTimerType(Qt::PreciseTimer)

默认的 Qt :: CoarseTimer 不太精确(间隔的5%)

The default Qt::CoarseTimer is less precise (5% of the interval)

这篇关于最准确的计时器Qt C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆