I need a timer to execute callbacks with relatively low resolution. What's the best way to implement such C++ timer class in Linux? Are there any libraries I could use?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
The timeval struct from the time.h header is what you are looking for. It has time in seconds and nanoseconds. So total time in nanoseconds is timeval.tv_sec * 1000000 + timeval.tv_usec. Easy enough, I think.
Try the clock_gettime() function, defined in time.h:
Typically you might call it like this:
here is a link for a timer class. u will only need to create timer and pass it value for auto reload or not. a pointer to call back function. and either if u want it to be handled by a thread or with signal. if u choose signal then u have to pass the signo also.
http://timerlinux.codeplex.com/
If u want to study more about timer or signals there is a good book called linux system programming. u will only have to read 3 chapters and its explaining it all.
If you're writing within a framework (Glib, Qt, Wx, ...), you'll already have an event loop with timed callback functionalities. I'll assume that's not the case.
If you're writing your own event loop, you can use the
gettimeofday
/select
pair (struct timeval
, microsecond precision) or theclock_gettime
/nanosleep
pair (struct timespec
, nanosecond precision) for your own event dispatcher. Even though latter interface is higher resolution, scheduling is never that accurate anyways, so take whatever fits best.Warning: I love C. I never write C++. I'm just pretending to know the language.
Disclaimer: written just now and totally untested. The basic idea is to keep events in a priority queue, wait until the first one, run it, and repeat.
Use the boost::asio library. It has both synchronous and asynchronous timers which call a callback.
http://www.boost.org/doc/libs/1_37_0/doc/html/boost_asio/tutorial.html