I made some test using multiple timers but with timerEvent
(QObject::setTimer()
).
The thing is, of course if you have multiple timers that interfere at some point (tick exactly in the same time) all your doStuffThatTake10ms
code will be 'queued' ... But the absolute precision of timers should remain over time. Here some code to try it out.
#ifndef MULTITIMER_H
#define MULTITIMER_H
#include <QObject>
#include <QTime>
class MultiTimer : public QObject
{
Q_OBJECT
public:
explicit MultiTimer(QObject *parent = 0);
void timerEvent(QTimerEvent *event);
private:
int timerId[4];
int interval[4];
int count[4];
QTime absoluteTimer;
};
#endif // MULTITIMER_H
Implementation .cpp
#include "MultiTimer.h"
#include <QTimerEvent>
#include <QTime>
#include <QDebug>
MultiTimer::MultiTimer(QObject *parent) :
QObject(parent)
{
interval[0] = 500;
interval[1] = 1000;
interval[2] = 1500;
interval[3] = 2000;
for( int i = 0; i < 4; i++)
timerId[i] = startTimer(interval[i]);
for( int i = 0; i < 4; i++)
count[i] = 0;
absoluteTimer.start();
}
void MultiTimer::timerEvent(QTimerEvent *event)
{
int id = -1;
for( int i = 0; i < 4; i++){
if( event->timerId() == timerId[i]){
id = i;
count[id]++;
break;
}
}
if( id != -1) {
qDebug() << "timer" << id
<< "interval" << interval[id]
<< "count" << count[id]
<< "total" << count[id]*interval[id]
<< "reference" << absoluteTimer.elapsed();
usleep(10000);
}
}
To try it out create a = QApllication()
and a MultiTimer
object and fire a.exec()
.
Result after 1 minute on linux
timer 1 interval 1000 count 59 total 59000 reference 59010
timer 0 interval 500 count 119 total 59500 reference 59500
timer 0 interval 500 count 120 total 60000 reference 60000
timer 1 interval 1000 count 60 total 60000 reference 60010
timer 3 interval 2000 count 30 total 60000 reference 60021
timer 2 interval 1500 count 40 total 60000 reference 60031
timer 0 interval 500 count 121 total 60500 reference 60500
As you can see the 121th tick of timer 0
is right on time at 60500ms
... but at 60000ms
all timers collide creating delayed execution.