Jean-Luc
Jean-Luc

Reputation: 3613

QTime or QTimer wait for timeout

I'm writting a Qt application, and I have a four hour loop (in a seperate thread). In that four hour loop, I have to:

  1. do stuff with the serial port;
  2. wait a fixed period of time;
  3. do some more stuff with the serial port;
  4. wait an arbitrary amount of time.
  5. when 500ms have past, do more stuff;
  6. Go to 1. and repeat for four hours.

Currently, my method of doing this is really bad, and crashes some computers. I have a whole bunch of code, but the following snippet basically shows the problem. The CPU goes to ~100% and eventually can crash the computer.

 void CRelayduinoUserControl::wait(int timeMS)
{
    int curTime = loopTimer->elapsed();
    while(loopTimer->elapsed() < curTime + timeMS);
}

I need to somehow wait for a particular amount of time to pass before continuing on with the program. Is there some function which will just wait for some arbitrary period of time while keeping all the timers going?

Upvotes: 1

Views: 9797

Answers (2)

David D
David D

Reputation: 1591

If you want to sleep in QT, use QTimer. Just connect the timeout signal from the timer to the slot that contains the code you want to do every x amount of time.

Upvotes: 1

Flynch
Flynch

Reputation: 84

IMO you should use the signal/slot mechanism in spite of waiting inside a while. Code could be something like that:

#define STATE_1 0x01
#define STATE_2 0x02
#define STATE_3 0x03
.....
QTimer * timer  = new QTimer();
connect(timer,SIGNAL(timeout()),SLOT(timerSlot()));
int state = STATE_1 ;
timer->timerSlot()
.... 


void timerSlot() { 
  switch(state) {
    case STATE_1:
      // do stuff with the serial port
      state = STATE_2;
      timer->start(time_to_wait_in_ms);
      break;
    case STATE_2:
      // do more stuff with the serial port
      state = STATE_3;
      timer->start(500);
      break; 
    case STATE_3:
      // do more stuff 
      state = STATE_1;
      timer->start(1000*60*60*4);
      break; 
  }  

Upvotes: 0

Related Questions