1

How can I call a function in C++ after a certain period of time or at a particular time?
I searched in Google and in Stackoverflow. I only found way to do this through SIGALARM handler.

Update 1:
P.S. I use Linux.
P.P.S. I haven't got any written code, because I want to know how to do that, before writing.<

MSalters
  • 173,980
  • 10
  • 155
  • 350
Dm3Ch
  • 621
  • 1
  • 10
  • 26
  • You could do it with `goto`s but it makes the code kinda look like spaghetti and tougher to follow sometimes. (I am assuming you want to do something before the return of a function or so) –  Aug 07 '14 at 09:34

5 Answers5

4

You'd probably want to do that in another throwaway thread, as waiting in the main thread would block your app. You can add the delay in that thread by using std::this_thread::sleep_for.

I.e.

using namespace std;
thread([]{this_thread::sleep_for(chrono::milliseconds(1000)); foo(); }).detach();
MSalters
  • 173,980
  • 10
  • 155
  • 350
2

The POSIX way of doing it in C is through setting a signal handler with SIGALARM and having in it the function that you want to be called. In this scenario, you give to the operative system (kind of) the responsibility to call you once the time has come.

The C++11 way of doing it is through std::thread and std::chrono. A very simple, and may be not complete example:

std::chrono::milliseconds duration( 2000 );
auto deferred_task = [duration] () { std::this_thread::sleep_for(duration); call_task(); }
std::thread t(deferred_task);

In this barebone exmple your program is multithreading, and one thread is responsible to make the deferred call (in another thread). You may want to join, to catch a return value, and whatever you want, synchronously or asynchronously.

You want to have a multithread application or do you require a single-thread signal C behaviour? This is quite critical and it will be your main constraint on your code style from here.

MariusSiuram
  • 3,380
  • 1
  • 21
  • 40
1

Try the answer to this question if you have access to the Boost libraries. You can either call your function periodically or as a one-off.

Community
  • 1
  • 1
CraigJones
  • 61
  • 3
0

Try to use timer. Or in linux use epoll. And something like waitforsingleobject in Windows.

sunnyleevip
  • 165
  • 1
  • 14
0

You can actually do it in a super simple way:

void example(void (*f)()) {
  struct defer {
    void (*f)();
    ~defer() { f(); }
  } _[[maybe_unused]] { f };
}
Duzy Chan
  • 51
  • 1
  • 3