Qt C++每秒运行一次代码
Qt C++ Run code every second
我需要每秒检查一次条件,然后运行函数。执行是异步的,因此不会产生任何问题。我可以在循环中的某个地方调用函数吗?我会在程序启动后获得时间并检查秒是否通过。我在哪里可以找到主循环?谢谢
使用 QTimer 可以解决这个问题:
QTimer* timer = new QTimer();
timer->setInterval(1000); //Time in milliseconds
//timer->setSingleShot(false); //Setting this to true makes the timer run only once
connect(timer, &QTimer::timeout, this, [=](){
//Do your stuff in here, gets called every interval time
});
timer->start(); //Call start() AFTER connect
//Do not call start(0) since this will change interval
此外(并且由于存在关于lambda函数对目标对象生存期的不安全性的争论(,当然可以将其连接到另一个对象中的插槽:
connect(timer, &QTimer::timeout, anotherObjectPtr, &AnotherObject::method);
请注意,此方法不应有参数,因为超时信号也是在没有参数的情况下定义的。
相关文章:
- 谷歌基准测试,如何只调用一次代码?
- 代码执行/CPU 速度每 2 秒减慢一次
- 代码只输出一次 std::vector,而不是多次输出
- 我如何使一行代码可以选择,但在已经选择过一次后不重新选择
- 循环在此代码中仅迭代一次,而在另一个代码中正确迭代
- Qt C++每秒运行一次代码
- 如何将.txt文件中的多维数组放入代码中,并一次打印一行
- 代码无限循环不能只打印一次
- 限制C++更新速率.为什么此代码每秒更新一次,而不是每秒更新 60 次
- 每 t 毫秒执行一次 c++ 代码
- C++ SQLite 查询只工作一次。我的代码有什么问题?
- 对于多少种类型的 x86 处理器,Ngen 和 .net 本机一次创建本机代码
- 从第二次调用开始在函数中执行一段代码
- 如何在没有外部标志的情况下只在循环中运行一次代码
- 如何在ubuntu中创建和运行一个脚本,该脚本每5分钟运行一次并关闭一个c代码
- 在没有默认构造函数的OpenMP中,每个线程执行一次代码
- 如何只执行一段代码一次
- 代码是打印相同的值时,它应该随机生成每一次,而且它不打印数组中的第一个值
- 在精确的时间运行代码,每小时运行一次
- 每X秒执行一次代码,但在事件发生时立即中断