I am not an experinced c++ programmer. So I just want to know how to implement timer and timertask just like java has in C++. I have tried timer_create
example that is in man page of timer_create but It is not working as per my requirement.
I want that after particualar time span an event should fire, and if specific condition fulfills then timer should be canceled.
Any help would be highly appreciated. Thanks, Yuvi.
This is generally a very difficult question, since you are inherently asking for some concurrent, or at least asynchronous processing.
The simplest, single-threaded solution is to use something like Posix's alarm(2)
. This will cause a signal to be sent to your process after a specified time. You need to register a signal handler (e.g. with signal(2)
), but you are subject to all its limitations (e.g. you must only call async-safe functions within the handler).
A second, single-threaded option is to use a select
-style (or epoll
-style) I/O loop and use a kernel timer file descriptor. This is a very recent Linux feature, though, so availability will vary.
Finally, the typical, general solution is to use multiple threads: Make a dedicated thread for the timer whose only purpose is to sleep for the set time span and then execute some code. For this you will have to bear the full weight of concurrent programming responsibilities, such as handling shared data, guaranteeing the absence of races, etc.
Some higher-level libraries like Boost.ASIO and the new standard library provide some nice timing mechanisms once you've decided to go down the multithreaded route.