X-Git-Url: https://git.dogcows.com/gitweb?a=blobdiff_plain;f=src%2Fmoof%2Ftimer.hh;fp=src%2Fmoof%2Ftimer.hh;h=d7a411bc48e82089891795db5602d2cfb42e4326;hb=831f04d4bc19a390415ac0bbac4331c7a65509bc;hp=0000000000000000000000000000000000000000;hpb=299af4f2047e767e5d79501c26444473bda64c64;p=chaz%2Fyoink diff --git a/src/moof/timer.hh b/src/moof/timer.hh new file mode 100644 index 0000000..d7a411b --- /dev/null +++ b/src/moof/timer.hh @@ -0,0 +1,121 @@ + +/*] Copyright (c) 2009-2010, Charles McGarvey [************************** +**] All rights reserved. +* +* vi:ts=4 sw=4 tw=75 +* +* Distributable under the terms and conditions of the 2-clause BSD license; +* see the file COPYING for a complete text of the license. +* +**************************************************************************/ + +#ifndef _MOOF_TIMER_HH_ +#define _MOOF_TIMER_HH_ + +/** + * \file timer.hh + * Functions for measuring time in a friendly unit. + */ + +#include + +#include +#include + +#include + + +namespace moof { + + +class timer +{ +public: + + enum mode + { + invalid = -1, + normal = 0, + absolute = 1, + repeat = 2 + }; + + typedef boost::function function; + + + timer() : + mode_(invalid) {} + + timer(const function& function, scalar seconds, mode mode = normal) + { + init(function, seconds, mode); + } + + ~timer() + { + invalidate(); + } + + void init(const function& function, scalar seconds, mode mode = normal); + + bool is_valid() const; + void invalidate(); + + void fire(); + + scalar seconds_remaining() const; + bool is_expired() const; + bool is_repeating() const; + + + /** + * Get the number of seconds since a fixed, arbitrary point in the + * past. + * \return Seconds. + */ + static scalar ticks(); + + + /** + * Put the thread to sleep for a certain period of time. If absolute + * is true, then it will sleep until seconds after the fixed time in + * the past. If absolute is false, it will sleep for seconds starting + * now. Unlike system sleep functions, this one automatically resumes + * sleep if sleep was interrupted by a signal. Therefore, calling this + * function is guaranteed to sleep for the requested amount of time + * (and maybe longer). + * \param seconds Number of seconds. + * \param mode The timer mode. + */ + static void sleep(scalar seconds, mode mode = normal); + + + static scalar next_expiration() + { + return gNextFire; + } + + static void fire_expired_timers(); + static void fire_expired_timers(scalar t); + + +private: + + static unsigned new_identifier(); + static scalar find_next_expiration(); + + function function_; + mode mode_; + scalar absolute_; + scalar interval_; + unsigned id_; + + static scalar gNextFire; + static std::map gTimers; +}; + + +} // namespace moof + +#endif // _MOOF_TIMER_HH_ +