I have an application where I need to have both an event loop and an explicit forever {} loop running within a QThread. An object which is created inside the forever {} loop (but only once, of course) contains a QTimer which is supposed to call one of the object's own methods when it times out.

That's probably as clear as mud, so here is some code:

Qt Code:
  1. class updater : public QObject
  2. {
  3. Q_OBJECT
  4. ..
  5. void startSomething()
  6. {
  7. ...
  8. if (!updateTimer)
  9. {
  10. updateTimer = new QTimer(this);
  11. updateTimer -> setSingleShot(true);
  12. updateTimer -> setInterval(UPDATE_INTERVAL);
  13. connect(updateTimer, SIGNAL(timeout()),
  14. this, SLOT(doSomething()), Qt::DirectConnection);
  15. }
  16. updateTimer -> start();
  17. }
  18.  
  19. public slots:
  20. void doSomething()
  21. {
  22. qDebug() << "Doing something";
  23. ...
  24. }
  25.  
  26. private:
  27. QTimer *updateTimer;
  28.  
  29. }
  30.  
  31. class worker : public QThread
  32. {
  33. Q_OBJECT
  34.  
  35. ...
  36.  
  37. private slots:
  38. void mainLoop()
  39. {
  40. forever
  41. {
  42. ...
  43. if (flagSet)
  44. {
  45. ud = new updater();
  46. unsetFlag();
  47. }
  48. ....
  49.  
  50. if (anotherFlagSet)
  51. {
  52. ud -> startSomething();
  53. unsetTheOtherFlag();
  54. }
  55. }
  56. }
  57.  
  58. private:
  59. void run()
  60. {
  61. {
  62. QTimer trigger;
  63. connect(&trigger, SIGNAL(timeout()),
  64. this, SLOT(mainServerLoop()), Qt::DirectConnection);
  65. trigger.setSingleShot(true);
  66. trigger.setInterval(0);
  67. trigger.start();
  68.  
  69. exec();
  70. }
  71.  
  72. updater *ud;
  73. }
To copy to clipboard, switch view to plain text mode 

The reason for such an obtuse structure is that the 'worker' QThread needs to control its own queue of requests for things it should work on, as the main thread sometimes sends it requests which, if not executed within a certain time, become obsolete and need to be deleted from the queue before new requests are sent. I realise that, were it not for this, I could just send requests to it via queued signals and everything would be much simpler.

Anyway, the reason for having the exec() command in the run() routine, as well as the forever{} loop, is to provide an event loop so that, if I understand correctly, the QTimer which belongs to the 'ud' object (of class 'updater') can work properly.

My problem, however, is that the QTimer which belongs to the 'ud' object does not, in fact, work properly; at least not all the time. The very first time that 'startSomething' is called, it works just as it is supposed to, but on subsequent occasions it doesn't seem to work at all. I have tried commenting-out the "updateTimer -> setSingleShot(true);" line, and putting "updateTimer -> stop()" into 'doSomething()' instead, and that makes no difference.

Can anyone help me to see what may be going wrong?

Thank you,
Stephen.