4 * Created on: Aug 10, 2012
20 TimerData() : time(0), target(0), refCount(0), justHit(false), repeat(false) { }
21 TimerData(Time target, bool repeat) : time(0), target(target), refCount(0), justHit(false), repeat(repeat) { }
37 ~Timer() { if (data) --data->refCount; }
38 Timer(TimerData<Time> *data) : data(data) { ++data->refCount; }
39 Timer(const Timer<Time> &other)
40 : data(other.data) { if (data) ++(data->refCount); }
41 Timer<Time> &operator =(const Timer<Time> &other) {
42 Timer<Time> temp(other);
46 void Swap(Timer<Time> &other) {
47 std::swap(data, other.data);
51 bool Finished() const {
52 return data && data->target != Time() && !data->repeat && data->time >= data->target;
54 bool Running() const {
55 return data && !Finished();
57 Time Elapsed() const {
58 return data ? data->time : Time();
60 Time Remaining() const {
61 return data ? (data->target - data->time) : Time();
63 int Iteration() const {
64 return (data && data->target > Time()) ? std::floor(data->time / data->target) : Time();
66 bool JustHit() const {
67 return data && data->justHit;
77 if (data) data->time = Time();
81 if (data->target > Time() && data->justHit) {
82 data->time -= data->target;
90 TimerData<Time> *data;
102 void Update(Time delta) {
103 for (typename std::list<TimerData<Time> >::iterator i(data.begin()), end(data.end()); i != end;) {
105 Time intervalTime(i->time);
106 if (i->repeat) while (intervalTime > i->target) intervalTime -= i->target;
107 i->justHit = intervalTime < i->target && intervalTime + delta >= i->target;
110 if (i->refCount <= 0) {
117 Timer<Time> StartTimer() {
118 data.push_back(TimerData<Time>());
119 return Timer<Time>(&data.back());
121 Timer<Time> StartCountdown(Time duration) {
122 data.push_back(TimerData<Time>(duration, false));
123 return Timer<Time>(&data.back());
125 Timer<Time> StartInterval(Time duration) {
126 data.push_back(TimerData<Time>(duration, true));
127 return Timer<Time>(&data.back());
131 std::list<TimerData<Time> > data;
137 #endif /* APP_TIMER_H_ */