Commit e1c7b86f781635e35a00bde4f49cbd5176d242b7

Authored by Wiebe Cazemier
1 parent fc2ba5b6

Use monotonic clock in Timer class

This fixes side effects when system time changes.
timer.cpp
... ... @@ -24,16 +24,13 @@ License along with FlashMQ. If not, see <https://www.gnu.org/licenses/>.
24 24  
25 25 void CallbackEntry::updateExectedAt()
26 26 {
27   - this->lastExecuted = currentMSecsSinceEpoch();
  27 + this->lastExecuted = std::chrono::steady_clock::now();
28 28 }
29 29  
30 30 uint64_t CallbackEntry::getNextCallMs() const
31 31 {
32   - int64_t elapsedSinceLastCall = currentMSecsSinceEpoch() - lastExecuted;
33   - if (elapsedSinceLastCall < 0) // Correct for clock drift
34   - elapsedSinceLastCall = 0;
35   -
36   - int64_t newDelay = this->interval - elapsedSinceLastCall;
  32 + const std::chrono::milliseconds elapsedSinceLastCall = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - lastExecuted);
  33 + int64_t newDelay = this->interval - elapsedSinceLastCall.count();
37 34 if (newDelay < 0)
38 35 newDelay = 0;
39 36 return newDelay;
... ...
... ... @@ -29,7 +29,7 @@ License along with FlashMQ. If not, see &lt;https://www.gnu.org/licenses/&gt;.
29 29  
30 30 struct CallbackEntry
31 31 {
32   - uint64_t lastExecuted = currentMSecsSinceEpoch(); // assume the first one executed to avoid instantly calling it.
  32 + std::chrono::time_point<std::chrono::steady_clock> lastExecuted = std::chrono::steady_clock::now();
33 33 uint64_t interval = 0;
34 34 std::function<void ()> f = nullptr;
35 35 std::string name;
... ...
utils.cpp
... ... @@ -294,14 +294,6 @@ bool startsWith(const std::string &amp;s, const std::string &amp;needle)
294 294 return s.find(needle) == 0;
295 295 }
296 296  
297   -int64_t currentMSecsSinceEpoch()
298   -{
299   - struct timeval te;
300   - gettimeofday(&te, NULL);
301   - int64_t milliseconds = te.tv_sec*1000LL + te.tv_usec/1000;
302   - return milliseconds;
303   -}
304   -
305 297 std::string getSecureRandomString(const ssize_t len)
306 298 {
307 299 std::vector<unsigned char> buf(len);
... ...
... ... @@ -65,7 +65,6 @@ void rtrim(std::string &amp;s);
65 65 void trim(std::string &s);
66 66 bool startsWith(const std::string &s, const std::string &needle);
67 67  
68   -int64_t currentMSecsSinceEpoch();
69 68 std::string getSecureRandomString(const ssize_t len);
70 69 std::string str_tolower(std::string s);
71 70 bool stringTruthiness(const std::string &val);
... ...