Qt timers cannot be stopped from another thread
Use QTimer
for this purpose and make use of SIGNALS
and SLOT
for the purpose of starting and stopping the timer/s from different threads. You can emit the signal from any thread and catch it in the thread which created the timer to act on it.
Since you say you are new to Qt, I suggest you go through some tutorials before proceeding so that you will know what Qt has to offer and don't end up trying to reinvent the wheel. :)
VoidRealms is a good starting point.
You have this problem because the timers in the static array is created in Thread X
, but started and stopped in Thread Y
. This is not allowed, because Qt rely on thread affinity to timeout timers.
You can either create, start stop in the same thread or use signal and slots to trigger start
and stop
operations for timers. The signal and slot solution is a bit problematic Because you have n
QTimer objects (Hint: how do you start the timer at position i
?)
What you can do instead is create and initialize the timer at position tmrnbr
in
TimerForFWUpgrade::set(unsigned char tmrnbr, unsigned int time){ singleTimer[tmrnbr] = new SingleTimer(0); singleTimer[tmrnbr]->set(time);}
which is executed by the same thread.
Futhermore, you don't need a SingleTimer
class. You are using Qt5, and you already have all you need at your disposal:
SingleTimer::isElapsed
is reallyQTimer::remainingTime() == 0
;SingleTimer::set
is reallyQTimer::setSingleShot(true); QTimer::start(time);
SingleTimer::slot_setElapsed
becomes useless- Thus
SingleTimer::SingleTimer
becomes useless and you dont need aSingleTimer
class anymore
I got the errors away after changing my timer concept. I'dont use anymore my SingleTimer module. Before the QTimer I won't let timeout and maybe because of that I run into problems. Now I have a cyclic QTimer that times out every 100ms in slot function I will then count the events. Below my working code:
TimerForFWUpgrade::TimerForFWUpgrade(QObject* parent) : QObject(parent), pTime(new QTimer(this)){ connect(pTime, SIGNAL(timeout()), this, SLOT(slot_handleTimer())); pTime->setTimerType(Qt::PreciseTimer); pTime->start(100);}void TimerForFWUpgrade::set(unsigned char tmrnbr, unsigned int time){ if(tmrnbr < NR_OF_TIMERS) { if(timeBase != 0) { myTimeout[tmrnbr] = time / timeBase; } else { myTimeout[tmrnbr] = 0; } myTimer[tmrnbr] = 0; myElapsed[tmrnbr] = false; myActive[tmrnbr] = true; }}char TimerForFWUpgrade::isElapsed(unsigned char tmrnbr){ QCoreApplication::processEvents(); if(tmrnbr < NR_OF_TIMERS) { if(true == myElapsed[tmrnbr]) { return 1; } else { return 0; } } else { return 0; // NOK }}void TimerForFWUpgrade::slot_handleTimer(){ for(UINT8 i = 0; i < NR_OF_TIMERS; i++) { if(myActive[i] == true) { myTimer[i]++; if(myTimeout[i] < myTimer[i]) { myTimer[i] = 0; myElapsed[i] = true; myActive[i] = false; } } }}