I have to do a C code to use two Qt timers:
- one as an alarm, after x seconds, call a c function alarm_finished().
- one to implement this: every second, call callback on_1s_event also defined in a c file.
I know that I should use two timers, and class QTimer but I'm not sure either to define the two timers in two different classes or not, and how can I guarantee that my timers are running in the same time, that one doesn't wait for the other. Thank you so much for enlightening me around this matter!
CodePudding user response:
QTimer doesn't promise to be exact, but if you are measuring with a resolution of seconds, it will be very good for normal uses.
how can I guarantee that my timers are running in the same time, that one doesn't wait for the other.
You don't. If alarm_finished
takes multiple seconds to run, there will be multiple seconds where on_1s_event
doesn't fire. Similarly if on_1s_event
takes more than a second to run, your system is not going to function correctly.
CodePudding user response:
Just for your reference. I am using two QTimers in a test class. In the 10th 1sec task its triggering the 10s alarm.
#define TWOTIMER_HPP
#include <QObject>
#include <QTimer>
#include <QDebug>
class MyTestObject: public QObject
{
Q_OBJECT
public:
MyTestObject(): timer_alarm(new QTimer()),
periodic_call(new QTimer())
{
periodic_call->setInterval(1000);
timer_alarm->setSingleShot(true);
timer_alarm->setInterval(10000);
connect(periodic_call, &QTimer::timeout, this, &MyTestObject::ProcessTask1s_event);
connect(timer_alarm, &QTimer::timeout, this, &MyTestObject::Invoke_Alarm);
timer_alarm->start();
periodic_call->start();
}
void ProcessTask1s_event()
{
qDebug() << "Process Task Ran ";
}
void Invoke_Alarm()
{
qDebug() << "Invoke Alarm Task Ran ";
}
private:
QTimer* timer_alarm;
QTimer* periodic_call;
};
#endif // TWOTIMER_HPP
CodePudding user response:
Since you supplied very sparse information, I'll keep this answer generic.
In your main window, you can create your timers with new QTimer(this)
as local variables (the this
will take care of freeing them upon destruction of the main window).
Then, you need to connect
the timeout event of the QTimer instances to the functions you want to call, such as this:
connect(timer1, &QTimer::timeout, &someCFunction);
Finally, you need to start
the timer with the required interval in milliseconds.
Please refer to the documentation at https://doc.qt.io/qt-5/qtimer.html for some more details.
Please also note, that Qt utilizes an 'EventLoop' mechanism, meaning that your functions will execute in the same 'thread context' as the receiving context (i.e. your main loop). As such, your events can be executed 'after one another', but never 'at the same time'.