wall_clock_timer.cc 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2018 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "base/timer/wall_clock_timer.h"
  5. #include <utility>
  6. #include "base/power_monitor/power_monitor.h"
  7. #include "base/time/clock.h"
  8. #include "base/time/default_clock.h"
  9. #include "base/time/default_tick_clock.h"
  10. #include "base/time/tick_clock.h"
  11. namespace base {
  12. WallClockTimer::WallClockTimer() = default;
  13. WallClockTimer::WallClockTimer(const Clock* clock, const TickClock* tick_clock)
  14. : timer_(tick_clock), clock_(clock ? clock : DefaultClock::GetInstance()) {}
  15. WallClockTimer::~WallClockTimer() {
  16. RemoveObserver();
  17. }
  18. void WallClockTimer::Start(const Location& posted_from,
  19. Time desired_run_time,
  20. OnceClosure user_task) {
  21. user_task_ = std::move(user_task);
  22. posted_from_ = posted_from;
  23. desired_run_time_ = desired_run_time;
  24. AddObserver();
  25. timer_.Start(posted_from_, desired_run_time_ - Now(), this,
  26. &WallClockTimer::RunUserTask);
  27. }
  28. void WallClockTimer::Stop() {
  29. timer_.Stop();
  30. user_task_.Reset();
  31. RemoveObserver();
  32. }
  33. bool WallClockTimer::IsRunning() const {
  34. return timer_.IsRunning();
  35. }
  36. void WallClockTimer::OnResume() {
  37. // This will actually restart timer with smaller delay
  38. timer_.Start(posted_from_, desired_run_time_ - Now(), this,
  39. &WallClockTimer::RunUserTask);
  40. }
  41. void WallClockTimer::AddObserver() {
  42. if (!observer_added_) {
  43. PowerMonitor::AddPowerSuspendObserver(this);
  44. observer_added_ = true;
  45. }
  46. }
  47. void WallClockTimer::RemoveObserver() {
  48. if (observer_added_) {
  49. PowerMonitor::RemovePowerSuspendObserver(this);
  50. observer_added_ = false;
  51. }
  52. }
  53. void WallClockTimer::RunUserTask() {
  54. DCHECK(user_task_);
  55. RemoveObserver();
  56. std::exchange(user_task_, {}).Run();
  57. }
  58. Time WallClockTimer::Now() const {
  59. return clock_->Now();
  60. }
  61. } // namespace base