granup.h 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #pragma once
  2. #include <util/datetime/base.h>
  3. #include <util/system/guard.h>
  4. #include <util/system/mutex.h>
  5. #include <util/system/spinlock.h>
  6. namespace NBus {
  7. template <typename TItem, typename TLocker = TSpinLock>
  8. class TGranUp {
  9. public:
  10. TGranUp(TDuration gran)
  11. : Gran(gran)
  12. , Next(TInstant::MicroSeconds(0))
  13. {
  14. }
  15. template <typename TFunctor>
  16. void Update(TFunctor functor, TInstant now, bool force = false) {
  17. if (force || now > Next)
  18. Set(functor(), now);
  19. }
  20. void Update(const TItem& item, TInstant now, bool force = false) {
  21. if (force || now > Next)
  22. Set(item, now);
  23. }
  24. TItem Get() const noexcept {
  25. TGuard<TLocker> guard(Lock);
  26. return Item;
  27. }
  28. protected:
  29. void Set(const TItem& item, TInstant now) {
  30. TGuard<TLocker> guard(Lock);
  31. Item = item;
  32. Next = now + Gran;
  33. }
  34. private:
  35. const TDuration Gran;
  36. TLocker Lock;
  37. TItem Item;
  38. TInstant Next;
  39. };
  40. }