6

Is is possible to call a function at a specific time in C++? For example, I would like to launch function doIt() when number_of_elapsed_milliseconds_since_application_start = x.

A cross-platform solution would be ideal.

Shawn
  • 10,931
  • 18
  • 81
  • 126

3 Answers3

3

In pure C++ probably not, you will need some OS specific code. But you can use a platform-independent OS-wrapper, like Qt (although this could be a bit of an overkill for your quite simple problem).

EDIT: The simplest thing you could do, is actively blocking the program in a loop, that constantly polls the current time, until the deadline is reached, but that is probably not a very useful solution. So without threads or some event-driven timer (as every OS should have) you won't get very far.

Christian Rau
  • 45,360
  • 10
  • 108
  • 185
3

Make a thread, put it to sleep until that time, and after the sleep, have it run that function.

George Kastrinis
  • 4,924
  • 4
  • 29
  • 46
  • 2
    +1, though I would note that we are not using real time OS, so the thread won't wake up at exactly the time scheduled, it'll be a bit off, how much depending on the current machine load. – Matthieu M. May 22 '11 at 11:55
1

This is what's considered a 'CallBack' function or a 'listener'. More information on implementing it can be found here: http://www.cprogramming.com/tutorial/function-pointers.html

Hope that helps.

DKWII
  • 11
  • 1