2

I need to periodically do a particular task and am currently using nanosleep.

The task needs to be run every second or every 10 seconds.

Is there a better way to do this than:

while(true)
{
 doTask();
 sleep();
}

Walter

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Walter
  • 1,290
  • 2
  • 21
  • 46
  • 2
    It has nothing to do with C++, it's OS dependent. Isn't precision of `sleep` good enough? – ruslik Jan 23 '11 at 03:33
  • possible duplicate of [C++ Cross-Platform High-Resolution Timer](http://stackoverflow.com/questions/1487695/c-cross-platform-high-resolution-timer) – James Black Jan 23 '11 at 03:47
  • My application isn't very stable - I don't see what's going on in the log file, but basically it should be saving a file every 10 seconds or so. I let it run a few hours and see that it skipped over a bunch of files it was supposed to save. How can I tell what's going on? – Walter Jan 23 '11 at 13:30

2 Answers2

1

One of the options could be to create a thread that will do the task with specified timeout.

kevin
  • 2,172
  • 3
  • 18
  • 19
0

You can use a thread library to create a thread which handle run the doTask(). Your main thread just keeps sleeping and runs every 1 second or 10 seconds.

This can be done with a QTimer and a QRunnable.

http://doc.qt.nokia.com/latest/qtimer.html

According to the dock, the resolution is around 1 ms in most cases. For your need, this should be sufficient.

Dat Chu
  • 10,822
  • 13
  • 58
  • 82