/*============================================================================== Copyright 2020 by Roland Rabien For more information visit www.rabiensoftware.com ==============================================================================*/ #pragma once class CoalescedTimer { public: CoalescedTimer () = default; void startTimer (int ms) { stopTimer(); delay = ms; sharedTimers->add (this); } void startTimerHz (int hz) { if (hz > 0) startTimer (1000 / hz); else stopTimer(); } void stopTimer() { sharedTimers->remove (this); delay = 0; } std::function onTimer; private: class SharedTimer : public Timer { public: void timerCallback() override { for (auto t : timers) if (t->onTimer) t->onTimer (); } Array timers; }; class SharedTimers { public: void add (CoalescedTimer* t) { auto itr = timers.find (t->delay); if (itr == timers.end()) { auto st = std::make_unique(); st->timers.add (t); st->startTimer (t->delay); timers[t->delay] = std::move (st); } else { itr->second->timers.add (t); } } void remove (CoalescedTimer* t) { auto itr = timers.find (t->delay); if (itr != timers.end()) { itr->second->timers.removeFirstMatchingValue (t); if (itr->second->timers.size() == 0) timers.erase (t->delay); } } std::map> timers; }; int delay = 0; SharedResourcePointer sharedTimers; };