X-Git-Url: http://git.tdb.fi/?p=libs%2Fcore.git;a=blobdiff_plain;f=source%2Ftime%2Ftimer.h;fp=source%2Ftime%2Ftimer.h;h=ef7ea8be0446f33a83af952ef33977a0f627e0c6;hp=0000000000000000000000000000000000000000;hb=e1ea831a640fba534e7e42e399f04cdf681ef8d3;hpb=0bcb8d4d6f33cbdad7b921cac787740bfe8e212e diff --git a/source/time/timer.h b/source/time/timer.h new file mode 100644 index 0000000..ef7ea8b --- /dev/null +++ b/source/time/timer.h @@ -0,0 +1,78 @@ +/* +This file is part of libmspframework +Copyright © 2006 Mikko Rasa, Mikkosoft Productions +Distributed under the LGPL +*/ +#ifndef MSP_TIME_TIMER_H_ +#define MSP_TIME_TIMER_H_ + +#include +#include +#include "../core/mutex.h" +#include "../core/semaphore.h" +#include "../core/thread.h" +#include "timedelta.h" +#include "timestamp.h" + +namespace Msp { +namespace Time { + +/** +A class for executing functions periodically. Every time the timeout is +reached, signal_timeout will be emitted. If the functor connected to this +signal returns true, the timer is rescheduled by incrementing the timeout +by the interval. Otherwise the timer is canceled. + +A separate thread is used for running the timers. All signal emissions will +happen in this thread - be careful with your variables. +*/ +class Timer +{ +public: + sigc::signal signal_timeout; + + Timer(const Time::TimeDelta &); + const Time::TimeStamp &get_timeout() const { return timeout; } + ~Timer(); +private: + /** + A thread to run the timers independently of the rest of the program. + */ + class Thread: public Msp::Thread + { + public: + Thread(); + void nudge(); + void finish(); + private: + bool done; + Semaphore sem; + + void main(); + }; + + /** + Proxy class to handle automatic starting and termination of the thread. + */ + class ThreadProxy + { + public: + ThreadProxy(): thread(0) { } + void nudge(); + ~ThreadProxy(); + private: + Thread *thread; + }; + + Time::TimeDelta interval; + Time::TimeStamp timeout; + + static ThreadProxy thread; + static Mutex set_mutex; + static std::set timers; +}; + +} // namespace Time +} // namespace Msp + +#endif