Overte C++ Documentation
OnceEvery.h
1 //
2 // Created by Bradley Austin Davis on 2016/04/19
3 // Copyright 2015 High Fidelity, Inc.
4 //
5 // Distributed under the Apache License, Version 2.0.
6 // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
7 //
8 
9 #include <stdint.h>
10 #include <functional>
11 
12 #include "../SharedUtil.h"
13 #include "../NumericalConstants.h"
14 
15 template <size_t MS = 1000>
16 class OnceEvery {
17 public:
18  OnceEvery(std::function<void()> f) : _f(f) { }
19 
20  bool maybeExecute() {
21  uint64_t now = usecTimestampNow();
22  if ((now - _lastRun) > (MS * USECS_PER_MSEC)) {
23  _f();
24  _lastRun = now;
25  return true;
26  }
27  return false;
28  }
29 
30 private:
31  uint64_t _lastRun { 0 };
32  std::function<void()> _f;
33 };