Shawn
Shawn

Reputation: 11391

How can I launch a function at a specific time in C++?

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.

Upvotes: 6

Views: 5965

Answers (3)

DKWII
DKWII

Reputation: 11

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.

Upvotes: 1

Christian Rau
Christian Rau

Reputation: 45948

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.

Upvotes: 3

George Kastrinis
George Kastrinis

Reputation: 5182

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

Upvotes: 3

Related Questions