有一个信号 - sendMessage(),它会触发一个函数--tartMessage(),如果我在一个镜头时间内得到信号太多次,会有一些问题,所以我想设置handleMessage( )每500毫秒只能运行一次。
有些朋友可以告诉我如何实现它吗?
答案 0 :(得分:3)
我这样做的方法是创建一个成员变量bool mMessageSendPending;
接下来我会创建一个成员变量QTimer mTimer;
在构造函数中,我会像这样设置计时器:
// Run lambda function on timer timeout
connect(&mTimer, &QTimer::timeout, [=](){
// This code will be run by timer
if(mMessageSendPending){
// This will never happen more frequent than 500ms
handleMessage();
// Reset to be ready for next send
mMessageSendPending=false;
}
});
// Start timer with interval of 500 ms
mTimer.start(500);
// Run lambda function on sendMessage received
connect(&mySender, &MySenderClass::sendMessage, [=](){
// Mark that we want to handle message.
// This may happen more frequent than once every 500ms
mMessageSendPending=true;
});
编辑:正如@Trevir指出的那样,跨线程边界并不安全。为了使其安全,建议将mMessageSendPending
中的QMutexLocker
的所有访问权限包含在匹配的QMutex
中,或者包装QAtomicInteger
以创建"原子布尔值& #34;
答案 1 :(得分:1)
处理此问题的常用方法是延迟手动处理邮件,例如像往常一样连接
connect(sender, &Sender::sendMessage, receiver, &Receiver::handleMessage);
并在接收方收集消息,延迟使用计时器
class Receiver : public QObject
{
Q_OBJECT
public:
void handleMessage(const QString &message);
....
private:
QStringList m_messages;
....
};
static const int DELAY = 500;
void Receiver::handleMessage(const QString &message)
{
const bool needsScheduling = m_messages.isEmpty();
m_messages.append(message);
if (needsScheduling) {
// schedule handling messages after a delay
// calls of handleMessage until this fires will add more messages
// to m_messages
QTimer::singleShot(DELAY, this, [this]() {
// do whatever you need to do with the messages
qDebug() << m_messages;
// clean up
m_messages.clear();
});
}
}
答案 2 :(得分:0)
QML的另一个解决方案:
Timer {
id: timer
property real period: 1000
property real started: 0
interval: 10
running: true
repeat: true
onTriggered: {
var s = new Date().getTime();
if((s - timer.started) > timer.period)
{
timer.started = s;
handleMessage();
}
}
function handleMessage()
{
console.log("handleMessage");
}
}
handleMessage()
调用的时间通常不超过1000毫秒,尽管onTriggered()
每10毫秒调用一次。